1 /* seq.c - Count from first to last, by increment.
3 * Copyright 2006 Rob Landley <rob@landley.net>
5 * http://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/seq.html
7 USE_SEQ(NEWTOY(seq, "<1>3?f:s:w[!fw]", TOYFLAG_USR|TOYFLAG_BIN))
11 depends on TOYBOX_FLOAT
14 usage: seq [-w|-f fmt_str] [-s sep_str] [first] [increment] last
16 Count from first to last, by increment. Omitted arguments default
17 to 1. Two arguments are used as first and last. Arguments can be
18 negative or floating point.
20 -f Use fmt_str as a printf-style floating point format string
21 -s Use sep_str as separator, default is a newline character
22 -w Pad to equal width with leading zeroes.
33 // Ensure there's one %f escape with correct attributes
34 static void insanitize(char *f)
36 char *s = next_printf(f, 0);
38 if (!s) error_exit("bad -f no %%f");
39 if (-1 == stridx("aAeEfFgG", *s) || (s = next_printf(s, 0))) {
40 // The @ is a byte offset, not utf8 chars. Waiting for somebody to complain.
41 error_exit("bad -f '%s'@%ld", f, s-f+1);
47 double first, increment, last, dd;
48 char *sep_str = "\n", *fmt_str = "%g";
51 // Parse command line arguments, with appropriate defaults.
52 // Note that any non-numeric arguments are treated as zero.
53 first = increment = 1;
55 case 3: increment = atof(toys.optargs[1]);
56 case 2: first = atof(*toys.optargs);
57 default: last = atof(toys.optargs[toys.optc-1]);
60 // Pad to largest width
61 if (toys.optflags & FLAG_w) {
63 int i, len, dot, left = 0, right = 0;
66 dd = (double []){first, increment, last}[i];
68 len = sprintf(toybuf, "%g", dd);
69 if ((s = strchr(toybuf, '.'))) {
71 if (left<dot) left = dot;
73 if (right<dot) right = dot;
74 } else if (len>left) left = len;
77 sprintf(fmt_str = toybuf, "%%0%d.%df", left+right+!!right, right);
79 if (toys.optflags & FLAG_f) insanitize(fmt_str = TT.fmt);
80 if (toys.optflags & FLAG_s) sep_str = TT.sep;
82 // Yes, we're looping on a double. Yes rounding errors can accumulate if
83 // you use a non-integer increment. Deal with it.
84 for (dd=first; (increment>0 && dd<=last) || (increment<0 && dd>=last);
87 if (dd != first) printf("%s", sep_str);
92 if (output) printf("\n");