uniq: add ascii implementation of -f and -s flags

This commit is contained in:
Tai Chi Minh Ralph Eastwood 2015-02-11 06:02:54 +00:00 committed by sin
parent 28e26bc688
commit bc2310376f

35
uniq.c
View File

@ -3,6 +3,7 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <unistd.h> #include <unistd.h>
#include <ctype.h>
#include "text.h" #include "text.h"
#include "util.h" #include "util.h"
@ -14,8 +15,11 @@ static void uniqfinish(void);
static const char *countfmt = ""; static const char *countfmt = "";
static int dflag = 0; static int dflag = 0;
static int uflag = 0; static int uflag = 0;
static int fskip = 0;
static int sskip = 0;
static char *prevline = NULL; static char *prevline = NULL;
static char *prevoffset = NULL;
static long prevlinecount = 0; static long prevlinecount = 0;
static void static void
@ -41,6 +45,12 @@ main(int argc, char *argv[])
case 'u': case 'u':
uflag = 1; uflag = 1;
break; break;
case 'f':
fskip = estrtonum(EARGF(usage()), 0, INT_MAX);
break;
case 's':
sskip = estrtonum(EARGF(usage()), 0, INT_MAX);
break;
default: default:
usage(); usage();
} ARGEND; } ARGEND;
@ -59,12 +69,29 @@ main(int argc, char *argv[])
return 0; return 0;
} }
static char *
uniqskip(char *l)
{
char *lo = l;
int f = fskip, s = sskip;
for (; f; --f) {
while (isblank(*lo))
lo++;
while (*lo && !isblank(*lo))
lo++;
}
for (; s && *lo && *lo != '\n'; --s, ++lo);
return lo;
}
static void static void
uniqline(char *l) uniqline(char *l)
{ {
char *loffset = l ? uniqskip(l) : l;
int linesequel = (!l || !prevline) int linesequel = (!l || !prevline)
? l == prevline ? l == prevline
: !strcmp(l, prevline); : !strcmp(loffset, prevoffset);
if (linesequel) { if (linesequel) {
++prevlinecount; ++prevlinecount;
@ -78,11 +105,13 @@ uniqline(char *l)
fputs(prevline, stdout); fputs(prevline, stdout);
} }
free(prevline); free(prevline);
prevline = NULL; prevline = prevoffset = NULL;
} }
if (l) if (l) {
prevline = estrdup(l); prevline = estrdup(l);
prevoffset = prevline + (loffset - l);
}
prevlinecount = 1; prevlinecount = 1;
} }