【问题标题】:Looping through files with a date pattern in name in Linux在 Linux 中循环使用名称中具有日期模式的文件
【发布时间】:2020-07-19 23:37:10
【问题描述】:

我正在尝试使用以下内容对附加了日期的任何文件进行 tar:

#!/bin/bash

createDate=[0-9]{4}-[0-9]{2}-[0-9]{2}

for file in $HOME/test/*.log.$createDate ; do
    log=$(basename $file)
    find . -type f | tar -zcvf  $log.tar $log
done

这应该 tar 任何在日志扩展名之后附加日期的文件,例如 test.log.2020-01-01。但是,我收到一个错误:

tar: *.log.[0-9]{4}-[0-9]{2}-[0-9]{2}: Cannot stat: No such file or directory

所以,它从字面上理解这个模式,作为一个字符串。我需要的是它在日志扩展名之后使用该模式来匹配具有该日期格式的任何文件。这最终将进入 logrotate 配置文件的 postrotate 部分,但我需要确保它首先工作。

【问题讨论】:

    标签: regex bash tar logrotate


    【解决方案1】:

    您正在将此模式用作 shell glob 模式:

    createDate=[0-9]{4}-[0-9]{2}-[0-9]{2}
    

    这实际上是一个正则表达式,而不是一个真正的 shell glob 模式。您的全局匹配失败并且只给出一个结果:*.log.[0-9]{4}-[0-9]{2}-[0-9]{2}

    可以通过以下方式更改此行为:

    shopt -s nullglob
    

    你的脚本应该修改成这样:

    shopt -s nullglob
    
    for file in $HOME/test/*.log.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]; do
        log=$(basename "$file")
        find . -type f | tar -zcvf "$log.tar" "$log"
    done
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 2019-06-17
      • 2022-12-12
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 2020-02-26
      相关资源
      最近更新 更多