gpt4 book ai didi

Linux bash 脚本 : Recurisely delete files if empty based on file format from user input

转载 作者:太空狗 更新时间:2023-10-29 12:10:31 25 4
gpt4 key购买 nike

<分区>

所以正如标题所描述的,我想递归地删除所有匹配用户给定的命名模式的文件,但前提是文件为空。这是我的尝试:

#!/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 脚本非常陌生,似乎无法弄清楚。抱歉这个笨拙的问题。我做了一些研究以找到答案,但没有找到我真正需要的东西。在此先感谢您的帮助。

编辑我找到了两种不同的解决方案。正如@David Z 的建议,可以通过第一个删除脚本的错误检查部分以及在查找函数中的 $_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 "$@",这样就可以将错误检查保留在脚本中。我不确定哪种方法更好,但如果我发现会再次更新。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com