shell 脚本查找早于 x 天的文件并删除它们(如果它们未在日志文件中列出)

shell script find file older than x days and delete them if they were not listet in log files

我是脚本新手,我需要一些 shell 脚本来执行以下操作:

  1. 查找早于 x 天的所有 .txt 文件
  2. 如果日志文件(文本文件和 gzip 文本文件)中未列出,则删除它们

我了解 find -mtimegrepzgrep 等的基础知识,但要在工作脚本中获取这些内容对我来说非常棘手。

我试过这样的事情:

#! /bin/sh
for file in $(find /test/ -iname '*.txt')
  do
  echo "$file" ls -l "$file"
  echo $(grep $file /test/log/log1)
done
IFS='
'
for i in `find /test/ -ctime +10`; do 
    grep -q $i log || echo $i   # replace echo with rm if satisfied
done
  • 设置 内部字段分隔符 文件名。

  • 查找 /test/ 文件夹中超过 10 天的所有文件。

  • Greps log 文件中的路径。

我会用这样的东西:

#!/bin/bash

#  is the number of days

log_files=$(ls /var/log)

files=$(find -iname "*.rb" -mtime -)

for f in $files; do
  found="false"
  base=$(basename $f)
  for logfile in $log_files; do
    res=$(zgrep $base $logfile)
    if [ "x$res" != "x" ]; then
      found="true"
      rm $f
    fi
    if [ "$found" = "true" ]; then
      break
    fi
  done
done

并称它为:

#> ./find_and_delete.sh 10

您可以创建一个小 bash 脚本来检查文件是否在日志中:

$ cat ~/bin/checker.sh 
#!/usr/bin/env bash
n=$(basename )
grep -q $n 
$ chmod +x ~/bin/checker.sh

然后在单个 find 命令中使用它:

$ find . -type f ! -exec ./checker.sh {} log \; -exec echo {} \;

这应该只打印要删除的文件。一旦确信它会做你想做的事:

$ find . -type f ! -exec ./checker.sh {} log \; -exec rm {} \;

删除它们。