Add -n support to sort(1)

This commit is contained in:
sin 2013-12-12 13:08:49 +00:00
parent 0b6b84886c
commit 544857623b
2 changed files with 15 additions and 2 deletions

5
sort.1
View File

@ -3,7 +3,7 @@
sort \- sort lines sort \- sort lines
.SH SYNOPSIS .SH SYNOPSIS
.B sort .B sort
.RB [ \-ru ] .RB [ \-nru ]
.RI [ file ...] .RI [ file ...]
.SH DESCRIPTION .SH DESCRIPTION
.B sort .B sort
@ -11,6 +11,9 @@ writes the sorted concatenation of the given files to stdout. If no file is
given, sort reads from stdin. given, sort reads from stdin.
.SH OPTIONS .SH OPTIONS
.TP .TP
.B \-n
perform a numeric sort.
.TP
.B \-r .B \-r
reverses the sort. reverses the sort.
.TP .TP

12
sort.c
View File

@ -11,13 +11,14 @@ static int linecmp(const char **, const char **);
static bool rflag = false; static bool rflag = false;
static bool uflag = false; static bool uflag = false;
static bool nflag = false;
static struct linebuf linebuf = EMPTY_LINEBUF; static struct linebuf linebuf = EMPTY_LINEBUF;
static void static void
usage(void) usage(void)
{ {
eprintf("usage: %s [-ru] [file...]\n", argv0); eprintf("usage: %s [-nru] [file...]\n", argv0);
} }
int int
@ -27,6 +28,9 @@ main(int argc, char *argv[])
FILE *fp; FILE *fp;
ARGBEGIN { ARGBEGIN {
case 'n':
nflag = true;
break;
case 'r': case 'r':
rflag = true; rflag = true;
break; break;
@ -63,6 +67,12 @@ main(int argc, char *argv[])
int int
linecmp(const char **a, const char **b) linecmp(const char **a, const char **b)
{ {
if (nflag) {
if (rflag)
return strtoul(*b, 0, 10) - strtoul(*a, 0, 10);
else
return strtoul(*a, 0, 10) - strtoul(*b, 0, 10);
}
return strcmp(*a, *b) * (rflag ? -1 : +1); return strcmp(*a, *b) * (rflag ? -1 : +1);
} }