【发布时间】:2017-09-28 09:07:04
【问题描述】:
正如标题所描述的,我想递归地删除所有与用户给出的命名模式匹配的文件,但前提是文件为空。这是我的尝试:
#!/bin/bash
_files="$1"
[ $# -eq 0 ] && { echo "Usage: $0 filename"; exit 1; }
[ ! -f "$_files" ] && { echo "Error: $0 no files were found which match given naming structure."; exit 2; }
for f in $(find -name $_files)
do
if [ -s "$f" ]
then
echo "$f has some data."
# do something as file has data
else
echo "$f is empty. Deleting file."
rm $f
fi
done
示例输出:
./remove_blank.sh *.o*
./Disp_variations_higher_0.o1906168 has some data.
./remove_blank.sh *.e*
./Disp_variations_higher_15.e1906183 is empty. Deleting file.
如您所见,代码有效,但一次只能用于一个文件。应该是一个相对简单的修复来让它工作,但我对 bash 脚本非常陌生,似乎无法弄清楚。对不起这个noobish问题。我做了一些研究以找到答案,但没有找到我真正需要的东西。提前感谢您的帮助。
编辑 我找到了两种不同的解决方案。正如@David Z 的建议,可以通过首先删除脚本的错误检查部分以及在 find 函数中的 $_files 变量周围加上引号来解决此问题。那么代码如下所示:
#!/bin/bash
_files=$1
[ $# -eq 0 ] && { echo "Usage: $0 filename"; exit 1; }
for f in $(find -name "$_files")
做
if [ -s $f ]
then
echo "$f has some data."
# do something as file has data
else
echo "$f is empty. Deleting file."
rm $f
fi
完成
或者,也可以简单地将 for 循环更改为 for f in "$@",这样可以将错误检查保留在脚本中。我不确定哪种方法更好,但如果我发现会再次更新。
【问题讨论】:
-
你需要在任何地方引用命令行参数和
$_files以防止扩展。 -
您不能在一个
find命令中执行此操作吗? -
当 files 和 recursive 在 bash 问题中关联时,显而易见的答案应该是
find。 -
有点隐蔽,但我在正文第4行使用了find模块:for f in $(find -name $_files)
-
我会期待像
find -name $_files -empty -delete