ShellScript,有没有更好的方法来“查找”具有特定名称和日期的文件?

5cg8jx4n  于 12个月前  发布在  Shell
关注(0)|答案(1)|浏览(98)

我有一个关于Linux和Shellscript的问题,我知道它不能从创建日期获取文件,只有修改日期,但如果我在文件名上获得创建日期呢?
例如,现在有一个文件夹,其中包括一些文件:

ABCADD01-20230801
ABCADD01-20230802
ABCADD01-20230803
ABCADD01-20230804
ABCADD02-20230801
ABCADD02-20230802
ABCAEE01-20230801
ABCAEE01-20230802
ABCAEE01-20230803
ABCAFF01-20230801
ABCAGG01-20230802

我需要找到文件名为“ABCADD”和创建日期为“2天前或更早”,并压缩这些文件。今天是20230804
我有一个想法是使用两个for循环:第一个循环是查找包含的文件名“ABCADD“,第二个循环是查找创建日期是两天前。

# Get the date for two days ago
two_days_ago=$(date -d "2 days ago" +%Y%m%d)

# Find the "ABCADD" files that were last modified two days ago, zip them
for file in $(find . -name 'ABCADD*' -type f ); do
    for file in $(find . -name '*$two_days_ago' -type f ); do
    echo "Zipping $file"
    gzip "$file"
    done
done

预期的最终结果应该是

ABCADD01-20230801
ABCADD01-20230802 
ABCADD02-20230801
ABCADD02-20230802

但是,我不能得到“两天前或更早”,只能得到具体的一天,这是20230802,还有一些bug。有更好的方法吗?

xwbd5t1u

xwbd5t1u1#

更新

下面是一个可能的解决方案,形式为date; find -exec awk | xargs gzip

two_days_ago=$(date -d '2 days ago' +%Y%m%d)

find . -name 'ABCADD*-20[0-9][0-9][0-9][0-9][0-9][0-9]' \
       -exec awk -v max="$two_days_ago" '
           BEGIN {
               for ( i = 1; i < ARGC; i++ ) {
                   n = split(ARGV[i], a, "-");
                   if ( a[n] <= max)
                       printf("%s%c", ARGV[i], 0);
               }
               exit;
           }
       ' {} + |
xargs -0 gzip

相关问题