sort question
Kurt Wall
kwall
Mon May 17 11:48:56 PDT 2004
Quoth Joel Hammer:
> I want to sort the contents of my .calendar file for pcal.
> The entries looks like this:
> 01/04/04 Item
> 1/3/3 Item
> And so on.
> I want to wind up with all the dates in proper order in the file.
> I have two problems I cannot figure out.
> First, when trying just to sort the fields numerically, using this sort
> of construction:
> sort -n -t'/' -n +1
> will sort the file numerically by the day of the month.
First, you want to normalize the appearance of the data. Here are
the contents of "calendar":
01/04/04
05/2/2
1/3/3
6/23/02
3/19/03
2/23/03
06/22/02
Now, an awk one-liner to normalize it
$ awk -F'/' 'printf("%02d/%02d/%02d\n", $1, $2, $3) }' < calendar
01/04/04
05/02/02
01/03/03
06/23/02
03/19/03
02/23/03
06/22/02
With the output normalized, it should be easy to sort:
$ awk -F'/' 'printf("%02d/%02d/%02d\n", $1, $2, $3) }' < calendar | sort -n
01/03/03
01/04/04
02/23/03
03/19/03
05/02/02
06/22/02
06/23/02
> But,
> sort -n -t'/' -n +0-2
> will sort the month (The first field) numerically
> but the next two fields are sorted like strings. Is there a way to make all
> the fields sort numerically?
See above.
> Second, is there way to sort the fields in random order, that is, year,
> month, and day?
Sort by key fields, appending "n" to each field to specify that it should
be sorted numerically. Thus, using "/" as the field separator and sorting
by the 2nd field and then the 1st field:
$ awk -F'/' 'printf("%02d/%02d/%02d\n", $1, $2, $3) }' < calendar \
> | sort -t'/' -k 2n -k 1n
05/02/02
01/03/03
01/04/04
03/19/03
06/22/02
02/23/03
06/23/02
Kurt
--
Only adults have difficulty with childproof caps.
More information about the Linux-users
mailing list