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
.SH SYNOPSIS
.B sort
.RB [ \-ru ]
.RB [ \-nru ]
.RI [ file ...]
.SH DESCRIPTION
.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.
.SH OPTIONS
.TP
.B \-n
perform a numeric sort.
.TP
.B \-r
reverses the sort.
.TP

12
sort.c
View File

@ -11,13 +11,14 @@ static int linecmp(const char **, const char **);
static bool rflag = false;
static bool uflag = false;
static bool nflag = false;
static struct linebuf linebuf = EMPTY_LINEBUF;
static void
usage(void)
{
eprintf("usage: %s [-ru] [file...]\n", argv0);
eprintf("usage: %s [-nru] [file...]\n", argv0);
}
int
@ -27,6 +28,9 @@ main(int argc, char *argv[])
FILE *fp;
ARGBEGIN {
case 'n':
nflag = true;
break;
case 'r':
rflag = true;
break;
@ -63,6 +67,12 @@ main(int argc, char *argv[])
int
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);
}