sbase/nl.c

82 lines
1.3 KiB
C
Raw Normal View History

2011-05-29 20:30:44 +00:00
/* See LICENSE file for copyright and license details. */
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "text.h"
#include "util.h"
2011-06-21 04:05:37 +00:00
static void nl(FILE *);
2011-05-29 20:30:44 +00:00
static char mode = 't';
static const char *sep = "\t";
static long incr = 1;
static regex_t preg;
2013-06-14 18:20:47 +00:00
static void
usage(void)
{
eprintf("usage: %s [-b style] [-i increment] [-s sep] [FILE...]\n",
argv0);
}
2011-05-29 20:30:44 +00:00
int
main(int argc, char *argv[])
{
FILE *fp;
2013-06-14 18:20:47 +00:00
char *r;
2011-05-29 20:30:44 +00:00
2013-06-14 18:20:47 +00:00
ARGBEGIN {
case 'b':
r = EARGF(usage());
mode = r[0];
if(r[0] == 'p') {
regcomp(&preg, &r[1], REG_NOSUB);
} else if(!strchr("ant", mode)) {
usage();
2011-05-29 20:30:44 +00:00
}
2013-06-14 18:20:47 +00:00
break;
case 'i':
incr = estrtol(EARGF(usage()), 0);
break;
case 's':
sep = EARGF(usage());
break;
default:
usage();
} ARGEND;
if(argc == 0) {
2011-06-21 04:05:37 +00:00
nl(stdin);
2013-06-14 18:20:47 +00:00
} else for(; argc > 0; argc--, argv++) {
if(!(fp = fopen(argv[0], "r")))
eprintf("fopen %s:", argv[0]);
2011-06-21 04:05:37 +00:00
nl(fp);
2011-05-29 20:30:44 +00:00
fclose(fp);
}
2013-06-14 18:20:47 +00:00
return 0;
2011-05-29 20:30:44 +00:00
}
void
2011-06-21 04:05:37 +00:00
nl(FILE *fp)
2011-05-29 20:30:44 +00:00
{
char *buf = NULL;
long n = 0;
size_t size = 0;
2013-06-14 18:20:47 +00:00
while(afgets(&buf, &size, fp)) {
2011-05-29 20:30:44 +00:00
if((mode == 'a')
2013-06-14 18:20:47 +00:00
|| (mode == 'p'
&& !regexec(&preg, buf, 0, NULL, 0))
|| (mode == 't' && buf[0] != '\n')) {
2011-05-29 20:30:44 +00:00
printf("%6ld%s%s", n += incr, sep, buf);
2013-06-14 18:20:47 +00:00
} else {
2011-05-29 20:30:44 +00:00
printf(" %s", buf);
2013-06-14 18:20:47 +00:00
}
}
2011-05-29 20:30:44 +00:00
free(buf);
}
2013-06-14 18:20:47 +00:00