【问题标题】:Bash multiple copy latest files with timestamp using regex使用正则表达式打击多个带有时间戳的最新文件
【发布时间】:2018-11-13 19:51:16
【问题描述】:

拜托,我需要重命名多个文件的帮助。我们每天生成 3 份报告中的一个应用程序,文件掩码为 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 命令。我想只用一次使用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

但是 echo 的结果看起来不太好。

请帮助解决问题?感谢您的任何建议

解决方案(感谢David Peltier):

for file in $(ls -t /mnt/server/OPEN_REPORT?_??????????????.csv | head -n3); do cp $file ${file%_*}.csv; done

【问题讨论】:

    标签: regex bash copy rename cp


    【解决方案1】:

    试试这个

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

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

    ${var%Pattern}, ${var%%Pattern}

    ${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

    【讨论】:

    • $(ls -1 /mnt/server/*.csv) 应该只是 /mnt/server/*.csvls 在这里没有任何用处。
    • 谢谢@TomFenech,不知道这是可能的..谢谢,但有一个不便之处,即使找不到任何东西,它也会打印一些东西
    • 另外你应该引用你的变量扩展,否则$file中的任何空格或其他尴尬的字符都会导致cp命令失败。
    • 谢谢。这完美无缺:for file in $(ls -t /mnt/server/OPEN_REPORT?_??????????????.csv | head -n3); do cp $file ${file%_*}.csv; done
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多