简体   繁体   English

在 Linux 中循环浏览名称中具有日期模式的文件

[英]Looping through files with a date pattern in name in Linux

I'm trying to use the following to tar any file that has a date appended to it:我正在尝试使用以下内容对任何附加了日期的文件进行 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

This should tar any file with a date appended after the log extension, like test.log.2020-01-01 .这应该 tar 任何在日志扩展名之后附加日期的文件,例如test.log.2020-01-01 However, I get an error:但是,我收到一个错误:

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

So, its reading this pattern literally, as a string.所以,它从字面上读取这个模式,作为一个字符串。 What I need is for it to use the pattern to match any file with that date format, after the log extension.我需要的是它在日志扩展名之后使用该模式来匹配具有该日期格式的任何文件。 This will eventually into the postrotate section for a logrotate configuration file, but I need to be sure it works first.这最终将进入 logrotate 配置文件的 postrotate 部分,但我需要确保它首先工作。

You are using this pattern as shell glob pattern:您将此模式用作 shell 全局模式:

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

Which is actually a regular expression and not really a shell glob pattern.这实际上是一个正则表达式,而不是真正的 shell glob 模式。 Your glob matching is failing and giving only one result: *.log.[0-9]{4}-[0-9]{2}-[0-9]{2}您的全局匹配失败并且只给出一个结果: *.log.[0-9]{4}-[0-9]{2}-[0-9]{2}

This behavior can be changed by using:可以使用以下方法更改此行为:

shopt -s nullglob

Your script should be modified to this:您的脚本应修改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM