代码之家  ›  专栏  ›  技术社区  ›  Bambi Bunny

使用regex对带有时间戳的多个副本最新文件进行bash

  •  0
  • Bambi Bunny  · 技术社区  · 8 年前

    请帮我重命名多个文件。用filemask生成日常三报表的一个应用 OPEN_REPORTn_yyyymmddHH24Miss.csv ,例如这样的列表:

    /mnt/server/OPEN_REPORT1_20180604130922.csv
    /mnt/server/OPEN_REPORT2_20180604130922.csv
    /mnt/server/OPEN_REPORT3_20180604130922.csv
    

    我希望这些文件复制为

    /mnt/server/OPEN_REPORT1.csv
    /mnt/server/OPEN_REPORT2.csv
    /mnt/server/OPEN_REPORT3.csv
    

    保留原始文件而不更改名称(因此,这意味着我只能列出最后3个文件)

    我有这个解决方案:

    cp $(ls -t /mnt/server/OPEN_REPORT1_* | head -n1) /mnt/server/OPEN_REPORT1.csv
    cp $(ls -t /mnt/server/OPEN_REPORT2_* | head -n1) /mnt/server/OPEN_REPORT2.csv
    cp $(ls -t /mnt/server/OPEN_REPORT3_* | head -n1) /mnt/server/OPEN_REPORT3.csv
    

    但是这个方法不是很有效,因为我用了更多的 cp 我需要的命令。我只想拷贝这些文件 内容提供商 命令和正则表达式。

    我正在尝试这样的解决方案:

    for file in $(ls -t /mnt/server/OPEN_REPORT?_??????????????.csv | head -n3); do echo ${file} | sed 's/OPEN_REPORT([0-9]{1})/$1/'; done
    

    但回声的结果看起来不太好。

    有什么解决办法吗?谢谢你的建议

    解决方案 (感谢 David Peltier ):

    for file in $(ls -t /mnt/server/OPEN_REPORT?_??????????????.csv | head -n3); do cp $file ${file%_*}.csv; done
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   David Peltier    8 年前

    试试这个

    for file in $(ls -1 /mnt/server/*.csv); do cp /mnt/server/$file /mnt/server/${file%_*}.csv;done
    

    bash可以进行替换,您不再需要使用sed。

    ${var%模式},${var%%模式}

    ${var%Pattern} Remove from $var the shortest part of $Pattern that matches the back end of $var.
    
    ${var%%Pattern} Remove from $var the longest part of $Pattern that matches the back end of $var. 
    

    https://www.tldp.org/LDP/abs/html/parameter-substitution.html

    推荐文章