1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28#define FOR_nl
29#include "toys.h"
30
31GLOBALS(
32 char *s, *n, *b;
33 long w, l, v;
34
35
36 long lcount;
37)
38
39static void do_nl(int fd, char *name)
40{
41 FILE *f = xfdopen(fd, "r");
42 int w = TT.w, slen = strlen(TT.s);
43
44 for (;;) {
45 char *line = 0;
46 size_t temp;
47 int match = *TT.b != 'n';
48
49 if (getline(&line, &temp, f) < 1) {
50 if (ferror(f)) perror_msg_raw(name);
51 break;
52 }
53
54 if (*TT.b == 'p') match = !regexec((void *)(toybuf+16), line, 0, 0, 0);
55 if (TT.l || *TT.b == 't')
56 if (*line == '\n') match = TT.l && ++TT.lcount >= TT.l;
57 if (match) {
58 TT.lcount = 0;
59 printf(toybuf, w, TT.v++, TT.s);
60 } else printf("%*c", (int)w+slen, ' ');
61 xprintf("%s", line);
62
63 free(line);
64 }
65
66 fclose(f);
67}
68
69void nl_main(void)
70{
71 char *clip = "";
72
73 if (!TT.s) TT.s = "\t";
74
75 if (!TT.n || !strcmp(TT.n, "rn"));
76 else if (!strcmp(TT.n, "ln")) clip = "-";
77 else if (!strcmp(TT.n, "rz")) clip = "0";
78 else error_exit("bad -n '%s'", TT.n);
79
80 sprintf(toybuf, "%%%s%s", clip, "*ld%s");
81
82 if (!TT.b) TT.b = "t";
83 if (*TT.b == 'p' && TT.b[1])
84 xregcomp((void *)(toybuf+16), TT.b+1,
85 REG_NOSUB | (toys.optflags&FLAG_E)*REG_EXTENDED);
86 else if (!strchr("atn", *TT.b)) error_exit("bad -b '%s'", TT.b);
87
88 loopfiles (toys.optargs, do_nl);
89}
90