+1 vote
in Operating Systems by (7k points)
I have a tab separated file which contains person_id and event_start_date. I want to sort the file by person_id and event_start_date so that the earlier event_date comes before the later event_date for each person sorted in ascending order.

The sorted file should also have header as the first record.

person_id       event_start_date
59001   2011-06-28
43302   2012-12-29
59001   2009-12-08
59001   2009-09-29
59001   2008-05-19
38201   2009-12-02
59001   2011-10-25
59001   2003-12-16
59001   2009-02-10

1 Answer

0 votes
by (13.6k points)

There may be several ways to sort the records in a file. You can try the following awk code.

awk 'NR==1; NR > 1 {print $0 | "sort -t\\t -n -k 1,1"}' yourfile > sorted_yourfile

It will first copy the header to your outputfile and then will append the sorted recrods. Your output file should look like this.

person_id       event_start_date
38201   2009-12-02
43302   2012-12-29
59001   2003-12-16
59001   2008-05-19
59001   2009-02-10
59001   2009-09-29
59001   2009-12-08
59001   2011-06-28
59001   2011-10-25

...