How do I sort a "MON_YYYY_day_NUM" time with UNIX tools?

Viewed 52

I'm wondering how do i sort this example based on time. I have already sorted it based on everything else, but i just cannot figure out how to go sort it using time (the 07:30 part for example).

My current code: sort -t"_" -k3n -k2M -k5n (still need to implement the time sort for the last sort)

What still needs to be sorted is the time:

Dunaj_Dec_2000_day_1_13:00.jpg
Rim_Jan_2001_day_1_13:00.jpg
Ljubljana_Nov_2002_day_2_07:10.jpg
Rim_Jan_2003_day_3_08:40.jpg
Rim_Jan_2003_day_3_08:30.jpg

Any help or just a point in the right direction is greatly appreciated!

2 Answers

Alphabetically; 24h time with a fixed number of digits is okay to sort using a plain alphabetic sort.

sort -t"_" -k3n -k2M -k5n -k6  # default sorting
sort -t"_" -k3n -k2M -k5n -k6V # version-number sort.

There's also a version sort V which would work fine.

I have to admit to shamelessly stealing from this answer on SO:

How to split log file in bash based on time condition

awk -F'[_:.]' '
BEGIN {
months["Jan"] = 1
months["Feb"] = 2
months["Mar"] = 3
months["Apr"] = 4
months["May"] = 5
months["Jun"] = 6
months["Jul"] = 7
months["Aug"] = 8
months["Sep"] = 9
months["Oct"] = 10
months["Nov"] = 11
months["Dec"] = 12
}
  { print mktime($3" "months[$2]" "$5" "$6" "$7" 00"), $0 }
'  input  | sort -n | cut -d\  -f2-
  • Use _:.\ field separator characters to parse each file name.
  • Initialize an associative array so we can map month names to numerical values (1-12)
  • Uses awk function mktime() - it takes a string in the format of "YYYY MM DD HH MM SS [ DST ]" as per https://www.gnu.org/software/gawk/manual/html_node/Time-Functions.html. Each line of input is print with a column prepending with the time in epoch seconds.
  • The results are piped to sort -n which will sort numerically the first column
  • Now that the results are sorted, we can remove the first column with cut
  • I have a MAC, so I had to use gawk to get the mktime function (it's not available with MacOS awk normally ). mawk is another option I've read.
Related