简体   繁体   中英

how to sort the timestamp in a filename in shell script

how do i sort the timestamp from oldest to newest that is before the _tm1.csv, the timestamp is always before the _tm1.csv, if _ is the delimiter, that is the second last segment , that will be timestamp.

alex_li_20140301121212_tm1.csv
alex_cf_li_20140302121212_tm1.csv
B_A_cf_li_20140303121212_tm1.csv

You can use:

awk -F_ '{print $(NF-1), $0}' file | sort -nk1 | cut -d' ' -f2-
alex_li_20140301121212_tm1.csv
alex_cf_li_20140302121212_tm1.csv
B_A_cf_li_20140303121212_tm1.csv
ls | sed 's/^.*_\([0-9]\+\)_.*$/\1,\0/' | sort -g | cut -d, -f 2

Here is an all-in-one solution using GNU awk :

awk -F_ '{
  ts[$(NF-1),$0]++
}
END {
  n = asorti(ts, ts_s);
  for(x = 1; x <= n; x++) {
    split(ts_s[x], tmp, SUBSEP);
      print tmp[1], tmp[2]
  }
}' file

or a one-liner if you prefer:

awk -F_ '{ts[$(NF-1),$0]++}END{n=asorti(ts,ts_s);for(x=1;x<=n;x++){split(ts_s[x],tmp,SUBSEP);print tmp[1],tmp[2]}}' file

Output (I modified your input file to demonstrate sorting)

$ cat file
alex_li_20140301121212_tm1.csv
alex_cf_li_20130302121212_tm1.csv
B_A_cf_li_20120303121212_tm1.csv

$ awk -F_ '{ts[$(NF-1),$0]++}END{n=asorti(ts,ts_s);for(x=1;x<=n;x++){split(ts_s[x],tmp,SUBSEP);print tmp[1],tmp[2]}}' file
20120303121212 B_A_cf_li_20120303121212_tm1.csv
20130302121212 alex_cf_li_20130302121212_tm1.csv
20140301121212 alex_li_20140301121212_tm1.csv

If you don't need timestamp in the output, you can just do print tmp[2] . Like:

$ awk -F_ '{ts[$(NF-1),$0]++}END{n=asorti(ts,ts_s);for(x=1;x<=n;x++){split(ts_s[x],tmp,SUBSEP);print tmp[2]}}' file
B_A_cf_li_20120303121212_tm1.csv
alex_cf_li_20130302121212_tm1.csv
alex_li_20140301121212_tm1.csv

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM