【问题标题】:Retrieve the date from a string path从字符串路径中检索日期
【发布时间】:2018-02-08 00:05:26
【问题描述】:

我有一个 for 循环,它递归地在目录中搜索文件。

for FILE in $(find /home/mydir/ -name '*.txt' -or -name '*.zip')

它们具有以下格式:

/home/mydir/subdir1/subdir2/22280317.txt

我想提取 .txt 左侧的 6 个数字作为日期,格式为 2017-03-28 我试过使用 awk 但是我遇到了问题,因为我想忽略开头的两位数字

【问题讨论】:

    标签: string awk sed grep


    【解决方案1】:

    这可能会解决您的问题

    find -name "*.txt" -exec sh -c 'f=${0%.txt}; l6=${f: -6}; date -d  "${l6: -2}-${l6:2:2}-${l6:0:2}" +"%Y-%m-%d" '  {} \;
    

    测试结果

    # create sample files
    [akshay@localhost test]$ touch 10280317.txt 
    [akshay@localhost test]$ touch 10170317.txt 
    [akshay@localhost test]$ touch 10170398.txt 
    
    # files created
    [akshay@localhost test]$ ls *.txt
    10170317.txt  10170398.txt 10280317.txt
    
    # output using date command which takes care of year
    # remove .txt
    # extract last 6 char
    # input year-mon-date to date command
    [akshay@localhost test]$ find -name "*.txt" -exec bash -c 'f=${0%.txt};  l6=${f: -6};  date -d  "${l6: -2}-${l6:2:2}-${l6:0:2}" +"%Y-%m-%d" '  {} \;
    2017-03-28
    2017-03-17
    1998-03-17
    

    如果你想显示文件名和日期,那么

    [akshay@localhost tmp]$ pwd
    /tmp
    
    [akshay@localhost tmp]$ find -name "*.txt" -exec bash -c 'f=${0%.txt};  l6=${f: -6}; echo $f $(date -d  "${l6: -2}-${l6:2:2}-${l6:0:2}" +"%Y-%m-%d") '  {} \; 
    ./tss/test/10280317 2017-03-28
    ./tss/test/10170317 2017-03-17
    ./tss/test/10170398 1998-03-17
    

    【讨论】:

      【解决方案2】:

      假设文件总是以相同的格式命名(22280317.txt),这是我的解决方案:

      awk -v FPAT="([0-9]{2})" 'BEGIN{ FS = "/"; OFS = "-" }{ x = substr($NF, 3, 6);  if (patsplit(x, a)) print a[1], a[2], "20"a[3] }'
      

      打印:

      28-03-2017
      

      【讨论】:

        【解决方案3】:

        使用 sed 表达式:

        find /home/mydir/ -name '*.txt' -or -name '*.zip' | sed -E 's/.*([0-9]{2})([0-9]{2})([0-9]{2})\.txt/20\3-\2-\1/' 
        

        【讨论】:

          猜你喜欢
          • 2016-05-03
          • 1970-01-01
          • 1970-01-01
          • 2013-06-23
          • 1970-01-01
          • 2012-02-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多