如何使用shell脚本查找特定文件类型的文件
我想在特定目录中找到特定的文件类型。一旦文件类型匹配,我需要删除该文件。因为我使用了下面的代码,但它不工作。你能建议解决这个问题的方法吗如何使用shell脚本查找特定文件类型的文件,shell,Shell,我想在特定目录中找到特定的文件类型。一旦文件类型匹配,我需要删除该文件。因为我使用了下面的代码,但它不工作。你能建议解决这个问题的方法吗 directory=/var/log/myFiles if [ -d $directory ] then for file in $directory/* do if [ -f $file ] then if [$file==*.log.1] then
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
实际上,您不需要脚本,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
因为如果
行是完全错误的,那么它应该是有问题的
比如:
更短更快的解决方案是使用
find
和xargs
:
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
谢谢你的更新。我已经在Jenkins FreeStyle作业中使用Shell脚本选项实现了您的代码。但是当*.log1文件在目录中不存在时,我遇到了一个错误。在我的情况下,无论文件是否应该存在于目录中,它都会删除。如果文件目录不存在,则Jenkins作业不应失败。你能提出解决方案吗?当然可以,但请先编辑你的问题,让大家知道你的要求已经改变了。
find /var/log/myFiles -type f -name '*.log.1' -print0 | xargs -0 rm