如何使用Shell脚本查找特定文件类型的文件

时间:2020-09-17 12:34:15

标签: shell

我想在特定目录中找到特定的文件类型。一旦文件类型匹配,我需要删除文件。由于我使用了以下代码,但它不起作用。您能为此建议解决方案吗?

directory=/var/log/myFiles

if [ -d $directory ]
then
   for file in $directory/*
      do  
       if [ -f $file ]
       then    
         if [$file==*.log.1]
         then
            rm file            
        fi
       fi
      done 
fi

2 个答案:

答案 0 :(得分:1)

您实际上不需要脚本,find + exec可以做到这一点:

find /var/log/myFiles -name "*.log.1" -exec echo rm {} \;

您的脚本失败:

$ ./script.sh
./script.sh: line 11: [/var/log/myFiles/a==*.log.1]: No such file or directory
./script.sh: line 11: [/var/log/myFiles/a.log.1==*.log.1]: No such file or directory

由于if行是完全错误的,应该是 喜欢:

if [[ "$file" == *.log.1 ]]

答案 1 :(得分:1)

更快,更快捷的解决方案是使用findxargs

find /var/log/myFiles -type f -name '*.log.1' | xargs rm

在进行如上所述的批量删除之前,我先进行安全检查,如下所示:

find /var/log/myFiles -type f -name '*.log1' | xargs ls -1

如果文件中包含空格或换行符,请使用上述命令的NUL分隔形式:

find /var/log/myFiles -type f -name '*.log.1' -print0 | xargs -0 rm