shell 脚本中的 ls 命令和文件大小

ls command and size of files in shell script

count=0;      #count for counting
IFS='
'
for x in `ls -l $input`;     #for loop using ls command
do 
a=$(ls -ls | awk '{print }')   #print[6] is sizes of  file
echo $a

b=`echo $a | awk '{split([=11=],numbers," "); print numbers[1]}'`
echo $b     
if [ $b -eq 0 ]          # b is only  size of a file
then
count=`expr $count + 1`   #if b is zero , the count will increase one by one
fi
echo $count
done

我想找到 0 个大小的文件。我使用 find 命令来做到这一点。第二件事是我想使用 ls 命令和 awk 计算大小为 0 的文件的数量。但它不是真正的代码。我的错误是什么?

如果文件大小不为零,-s 测试为真。如果该文件测试失败,请增加空文件数。

empty_files=0   
for f in "$input"/*; do
    [ -s "$f" ] || : $(( empty_files++ ))
done

你的主要错误是 parsing ls!

如果您想查找(常规)空文件,并且您有支持 -empty 谓词的 find 版本,请使用它:

find . -type f -empty

请注意,这也会在子文件夹中递归;如果你不想这样,使用:

find . -maxdepth 1 -type f -empty

(假设你的find也支持-maxdepth)。

如果您只想计算您有多少空(常规)文件:

find . -maxdepth 1 -type f -empty -printf x | wc -m

并且如果你想同时执行这两个操作,即打印出名称或将它们保存在一个数组中以备将来使用,并计算它们:

empty_files=()
while IFS= read -r -d '' f; do
    empty_files+=( "$f" )
done < <(find . -maxdepth 1 -type f -empty -print0)
printf 'There are %d empty files:\n' "${#empty_files[@]}"
printf '   %s\n' "${empty_files[@]}"

如果 Bash≥4.4,您可以使用 mapfile 而不是 while-read 循环:

mapfile -t -d '' empty_files < <(find . -maxdepth 1 -type f -empty -print0)
printf 'There are %d empty files:\n' "${#empty_files[@]}"
printf '   %s\n' "${empty_files[@]}"

对于 POSIX 兼容的方式,使用带有 -s 选项的 test

find . -type f \! -exec test -s {} \; -print

如果您不想递归到子目录,则必须 -prune 它们:

find . \! -name . -prune -type f \! -exec test -s {} \; -print

如果你想数一数:

find . \! -name . -prune -type f \! -exec test -s {} \; -exec printf x | wc -m

这里,如果你想执行这两个操作(计算它们并保存在一个数组中以备后用),使用前面的while-read循环(或mapfile 如果你生活在未来)用这个 find:

find . \! -name . -prune -type f \! -exec test -s {} \; -exec printf '%s[=18=]' {} \;

另请参阅 以获取纯 shell 解决方案(需要进行细微调整以符合 POSIX 标准)。


关于您的评论

I want to count and delete [empty files]. How can I do that at the same time?

如果您有 GNU find(或支持所有优点的 find):

find . -maxdepth 1 -type f -empty -printf x -delete | wc -m

如果没有,

find . \! -name . -prune -type f \! -exec test -s {} \; -printf x -exec rm {} \; | wc -m

确保-delete(或-exec rm {} \;)谓词在末尾! 不要交换谓词的顺序!