Implement nl -v startnum

This commit is contained in:
sin 2015-02-20 12:05:54 +00:00
parent 028b0c206f
commit 13e4231f4c
3 changed files with 18 additions and 7 deletions

2
README
View File

@ -48,7 +48,7 @@ The following tools are implemented ('*' == finished, '#' == UTF-8 support,
=* mktemp non-posix none =* mktemp non-posix none
=* mv yes none (-i) =* mv yes none (-i)
=* nice yes none =* nice yes none
= nl no -d, -f, -h, -l, -n, -p, -v, -w = nl no -d, -f, -h, -l, -n, -p, -w
=* nohup yes none =* nohup yes none
#* paste yes none #* paste yes none
=* printenv non-posix none =* printenv non-posix none

7
nl.1
View File

@ -1,4 +1,4 @@
.Dd December 4, 2014 .Dd February 20, 2015
.Dt NL 1 .Dt NL 1
.Os sbase .Os sbase
.Sh NAME .Sh NAME
@ -9,6 +9,7 @@
.Op Fl b Ar type .Op Fl b Ar type
.Op Fl i Ar incr .Op Fl i Ar incr
.Op Fl s Ar sep .Op Fl s Ar sep
.Op Fl v Ar startnum
.Op Ar file .Op Ar file
.Sh DESCRIPTION .Sh DESCRIPTION
.Nm .Nm
@ -41,6 +42,10 @@ Defines the increment between numbered lines.
.It Fl s Ar sep .It Fl s Ar sep
Defines the string used to separate line numbers and lines. By default this is Defines the string used to separate line numbers and lines. By default this is
a tab. a tab.
.It Fl v Ar startnum
Start counting from
.Ar startnum
instead of the default 1.
.El .El
.Sh SEE ALSO .Sh SEE ALSO
.Xr pr 1 .Xr pr 1

16
nl.c
View File

@ -9,6 +9,7 @@
static char mode = 't'; static char mode = 't';
static const char *sep = "\t"; static const char *sep = "\t";
static size_t startnum = 1;
static size_t incr = 1; static size_t incr = 1;
static regex_t preg; static regex_t preg;
@ -16,15 +17,17 @@ void
nl(const char *name, FILE *fp) nl(const char *name, FILE *fp)
{ {
char *buf = NULL; char *buf = NULL;
size_t n = 0, size = 0; size_t size = 0;
while (getline(&buf, &size, fp) != -1) { while (getline(&buf, &size, fp) != -1) {
if ((mode == 'a') if ((mode == 'a')
|| (mode == 'p' && !regexec(&preg, buf, 0, NULL, 0)) || (mode == 'p' && !regexec(&preg, buf, 0, NULL, 0))
|| (mode == 't' && buf[0] != '\n')) || (mode == 't' && buf[0] != '\n')) {
printf("%6ld%s%s", n += incr, sep, buf); printf("%6ld%s%s", startnum, sep, buf);
else startnum += incr;
} else {
printf(" %s", buf); printf(" %s", buf);
}
} }
free(buf); free(buf);
if (ferror(fp)) if (ferror(fp))
@ -34,7 +37,7 @@ nl(const char *name, FILE *fp)
static void static void
usage(void) usage(void)
{ {
eprintf("usage: %s [-b type] [-i incr] [-s sep] [file]\n", argv0); eprintf("usage: %s [-b type] [-i incr] [-s sep] [-v startnum] [file]\n", argv0);
} }
int int
@ -58,6 +61,9 @@ main(int argc, char *argv[])
case 's': case 's':
sep = EARGF(usage()); sep = EARGF(usage());
break; break;
case 'v':
startnum = estrtonum(EARGF(usage()), 0, MIN(LLONG_MAX, SIZE_MAX));
break;
default: default:
usage(); usage();
} ARGEND; } ARGEND;