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

b=`echo $a | awk '{split($0,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的数量。但它不是真正的代码。我的错误是什么?ls shell脚本中的文件命令和大小

+4

[不要解析'ls']的输出(http://mywiki.wooledge.org/ParsingLs)。 –

+0

我不知道其他用法。 Ls是不正确的? @gniourf_gniourf – esrtr

+1

@lurker即使不推荐这样做,因为如果任何文件名包含换行符,则输出的行数不是文件的数量。 – chepner

回答

1

你的主要错误是你是parsing ls

如果你想发现是空的,如果你有一个版本的find支持-empty谓语,使用(普通)文件:

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兼容的方式,使用test-s选项:

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 - 与此findread环(或mapfile如果你生活在未来):

find . \! -name . -prune -type f \! -exec test -s {} \; -exec printf '%s\0' {} \; 

另见chepner's answer对于纯壳溶液(需要较小的调整,以符合POSIX标准)。


关于你的评论

我要计数,并删除[空文件。我怎么能在同一时间做到这一点?

如果你有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 {} \;)谓词最后! 不交换谓词的顺序!

+0

我想计数并删除0个字节。我怎么能在同一时间做到这一点? – esrtr

+0

@esrtr查看帖子的底部。 –

2

如果文件的大小非零,则-s测试为真。如果该测试对文件失败,请增加空文件数量。

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