简体   繁体   中英

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:

#!/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 . 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.

You are using this pattern as shell glob pattern:

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

Which is actually a regular expression and not really a shell glob pattern. Your glob matching is failing and giving only one result: *.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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