【问题标题】:how to sort the timestamp in a filename in shell script如何在shell脚本中对文件名中的时间戳进行排序
【发布时间】:2014-03-05 04:20:32
【问题描述】:

我如何将_tm1.csv之前的时间戳从最旧到最新排序,时间戳总是在_tm1.csv之前,如果_是分隔符,即倒数第二个段,那将是时间戳。

alex_li_20140301121212_tm1.csv
alex_cf_li_20140302121212_tm1.csv
B_A_cf_li_20140303121212_tm1.csv

【问题讨论】:

    标签: linux oracle shell


    【解决方案1】:

    你可以使用:

    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
    

    【讨论】:

      【解决方案2】:
      ls | sed 's/^.*_\([0-9]\+\)_.*$/\1,\0/' | sort -g | cut -d, -f 2
      

      【讨论】:

        【解决方案3】:

        这是使用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
        

        如果您愿意,也可以使用单线:

        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
        

        输出(我修改了您的输入文件以演示排序)

        $ 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
        

        如果您在输出中不需要timestamp,您可以直接使用print tmp[2]。喜欢:

        $ 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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-12-27
          • 2021-04-22
          • 1970-01-01
          • 1970-01-01
          • 2013-07-11
          • 1970-01-01
          • 1970-01-01
          • 2011-08-26
          相关资源
          最近更新 更多