Bash shell脚本查找早于x天的文件,并在日志文件中未列出这些文件时将其删除

Bash shell脚本查找早于x天的文件,并在日志文件中未列出这些文件时将其删除,bash,shell,find,sh,Bash,Shell,Find,Sh,我是一个脚本新手,我需要一个小shell脚本来执行以下操作: 查找所有早于x天的.txt文件 如果日志文件(textfiles和gzip textfiles)中未列出它们,则将其删除 我知道有关find-mtime、grep、zgrep等的基本知识,但要在工作脚本中实现这一点对我来说非常棘手 我试过这样的方法: #! /bin/sh for file in $(find /test/ -iname '*.txt') do echo "$file" ls -l "$file" echo

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

  • 查找所有早于x天的.txt文件
  • 如果日志文件(textfiles和gzip textfiles)中未列出它们,则将其删除
  • 我知道有关
    find-mtime
    grep
    zgrep
    等的基本知识,但要在工作脚本中实现这一点对我来说非常棘手

    我试过这样的方法:

    #! /bin/sh
    for file in $(find /test/ -iname '*.txt')
      do
      echo "$file" ls -l "$file"
      echo $(grep $file /test/log/log1)
    done
    
    #!/bin/bash
    
    # $1 is the number of days
    
    log_files=$(ls /var/log)
    
    files=$(find -iname "*.rb" -mtime -$1)
    
    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
    
    • 为中包含空格的案例设置内部字段分隔符 文件名

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

    • Greps
      log
      文件中的路径


    我会用这样的方法:

    #! /bin/sh
    for file in $(find /test/ -iname '*.txt')
      do
      echo "$file" ls -l "$file"
      echo $(grep $file /test/log/log1)
    done
    
    #!/bin/bash
    
    # $1 is the number of days
    
    log_files=$(ls /var/log)
    
    files=$(find -iname "*.rb" -mtime -$1)
    
    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 $1)
    grep -q $n $2
    $ chmod +x ~/bin/checker.sh
    
    然后在单个
    find
    命令中使用它:

    $ find . -type f ! -exec ./checker.sh {} log \; -exec echo {} \;
    
    这应该只打印要删除的文件。一旦确信它能满足您的需求:

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

    删除它们。

    您到目前为止做了什么,结果如何?它尝试了类似的方法#/文件的bin/sh,单位为$(find/test/-iname'*.txt');完成echo“$file”ls-l“$file”echo$(grep$file/test/log/log1)吗