Reputation: 227
I have a file with date field like this.
20|1|124|Mar 19 2016 3:00AM
20|1|144|Mar 19 2016 2:00PM
43|1|146|Mar 19 2016 5:30AM
42|1|158|Mar 19 2016 1:50PM
40|1|15|Mar 19 2016 2:30AM
I want to sort by date field, such that the AM will come before PM. so far I have this:
sort -t"|" -k4 testfile.
But i am not sure how to sort the "AM" and "PM" portion. Any help is appreciated.
Upvotes: 1
Views: 326
Reputation: 785631
You can use:
while read -r; do
IFS='|' read -ra arr <<< "$REPLY"
date -d "${arr[-1]}" "+$REPLY#%s"
done < file | sort -t# -k2 | cut -d# -f1
40|1|15|Mar 19 2016 2:30AM
20|1|124|Mar 19 2016 3:00AM
43|1|146|Mar 19 2016 5:30AM
42|1|158|Mar 19 2016 1:50PM
20|1|144|Mar 19 2016 2:00PM
Using date
command we parse last field in your pipe delimited field and add EPOCH value in each line delimited by #
. Then using sort
we do the sorting by 2nd field (EPOCH value) and finally using cut
we discard value after #
.
Upvotes: 1
Reputation: 15461
You can use a temporary delimiter (ie |
) to make AM
/PM
a column that can be used as a sort field :
$ cat sourcefile | sed 's/\(.\)M$/|\1M/' | sort -t"|" -k5 -k4 | sed 's/|\(.\)M/\1M/'
40|1|15|Mar 19 2016 2:30AM
20|1|124|Mar 19 2016 3:00AM
43|1|146|Mar 19 2016 5:30AM
42|1|158|Mar 19 2016 1:50PM
20|1|144|Mar 19 2016 2:00PM
Upvotes: 1