nl: add -l option

This commit is contained in:
Quentin Rameau 2015-03-10 12:49:56 +01:00 committed by sin
parent a8bd21c0ab
commit 82bebf8ce7
3 changed files with 32 additions and 10 deletions

2
README
View File

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

3
nl.1
View File

@ -8,6 +8,7 @@
.Nm
.Op Fl b Ar type
.Op Fl i Ar incr
.Op Fl l Ar num
.Op Fl n Ar format
.Op Fl s Ar sep
.Op Fl v Ar startnum
@ -41,6 +42,8 @@ a regular expression as defined in
.El
.It Fl i Ar incr
Defines the increment between numbered lines.
.It Fl l Ar num
Specify the number of adjacent blank lines to be considered as one. Default is 1.
.It Fl n Ar format
Specify the line number output format.
The

37
nl.c
View File

@ -8,11 +8,13 @@
#include "text.h"
#include "util.h"
#define FORMAT_LN "%-*ld%s%s"
#define FORMAT_RN "%*ld%s%s"
#define FORMAT_RZ "%0*ld%s%s"
/* formats here specify line number and separator (not line content) */
#define FORMAT_LN "%-*ld%s"
#define FORMAT_RN "%*ld%s"
#define FORMAT_RZ "%0*ld%s"
static char mode = 't';
static int blines = 1;
static const char *format = FORMAT_RN;
static const char *sep = "\t";
static int width = 6;
@ -24,17 +26,31 @@ static void
nl(const char *name, FILE *fp)
{
char *buf = NULL;
int donumber, bl = 1;
size_t size = 0;
while (getline(&buf, &size, fp) != -1) {
if ((mode == 'a')
|| (mode == 'p' && !regexec(&preg, buf, 0, NULL, 0))
|| (mode == 't' && buf[0] != '\n')) {
printf(format, width, startnum, sep, buf);
donumber = 0;
if ((mode == 't' && buf[0] != '\n')
|| (mode == 'p' && !regexec(&preg, buf, 0, NULL, 0))) {
donumber = 1;
} else if (mode == 'a') {
if (buf[0] == '\n' && bl < blines) {
++bl;
} else {
donumber = 1;
bl = 1;
}
}
if (donumber) {
printf(format, width, startnum, sep);
startnum += incr;
} else {
printf(" %s", buf);
printf("%*s", width, "");
}
printf("%s", buf);
}
free(buf);
if (ferror(fp))
@ -44,7 +60,7 @@ nl(const char *name, FILE *fp)
static void
usage(void)
{
eprintf("usage: %s [-b type] [-i incr] [-n format] [-s sep] [-v startnum] [-w width] [file]\n", argv0);
eprintf("usage: %s [-b type] [-i incr] [-l num] [-n format] [-s sep] [-v startnum] [-w width] [file]\n", argv0);
}
int
@ -65,6 +81,9 @@ main(int argc, char *argv[])
case 'i':
incr = estrtonum(EARGF(usage()), 0, MIN(LLONG_MAX, SIZE_MAX));
break;
case 'l':
blines = estrtonum(EARGF(usage()), 0, UINT_MAX);
break;
case 'n':
format = EARGF(usage());
if (!strcmp(format, "ln"))