2015-11-01 90 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