sbase

suckless unix tools
git clone git://git.2f30.org/sbase
Log | Files | Refs | README | LICENSE

commit 82bebf8ce7a0f59e9d99c2b721f8b17b945a4aaa
parent a8bd21c0abe727d3292ecdb533cb308cac408072
Author: Quentin Rameau <quinq@quinq.eu.org>
Date:   Tue, 10 Mar 2015 12:49:56 +0100

nl: add -l option

Diffstat:
MREADME | 2+-
Mnl.1 | 3+++
Mnl.c | 37++++++++++++++++++++++++++++---------
3 files changed, 32 insertions(+), 10 deletions(-)

diff --git a/README b/README @@ -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 diff --git a/nl.1 b/nl.1 @@ -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 diff --git a/nl.c b/nl.c @@ -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"))