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

5cg8jx4n  于 2023-10-23  发布在  Shell
关注(0)|答案(1)|浏览(155)

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

  1. ABCADD01-20230801
  2. ABCADD01-20230802
  3. ABCADD01-20230803
  4. ABCADD01-20230804
  5. ABCADD02-20230801
  6. ABCADD02-20230802
  7. ABCAEE01-20230801
  8. ABCAEE01-20230802
  9. ABCAEE01-20230803
  10. ABCAFF01-20230801
  11. ABCAGG01-20230802

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

  1. # Get the date for two days ago
  2. two_days_ago=$(date -d "2 days ago" +%Y%m%d)
  3. # Find the "ABCADD" files that were last modified two days ago, zip them
  4. for file in $(find . -name 'ABCADD*' -type f ); do
  5. for file in $(find . -name '*$two_days_ago' -type f ); do
  6. echo "Zipping $file"
  7. gzip "$file"
  8. done
  9. done

预期的最终结果应该是

  1. ABCADD01-20230801
  2. ABCADD01-20230802
  3. ABCADD02-20230801
  4. ABCADD02-20230802

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

xwbd5t1u

xwbd5t1u1#

更新

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

  1. two_days_ago=$(date -d '2 days ago' +%Y%m%d)
  2. find . -name 'ABCADD*-20[0-9][0-9][0-9][0-9][0-9][0-9]' \
  3. -exec awk -v max="$two_days_ago" '
  4. BEGIN {
  5. for ( i = 1; i < ARGC; i++ ) {
  6. n = split(ARGV[i], a, "-");
  7. if ( a[n] <= max)
  8. printf("%s%c", ARGV[i], 0);
  9. }
  10. exit;
  11. }
  12. ' {} + |
  13. xargs -0 gzip
展开查看全部

相关问题