你的主要錯誤是你是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
- 與此find
read
環(或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 {} \;
)謂詞最後! 不交換謂詞的順序!
[不要解析'ls']的輸出(http://mywiki.wooledge.org/ParsingLs)。 –
我不知道其他用法。 Ls是不正確的? @gniourf_gniourf – esrtr
@lurker即使不推薦這樣做,因爲如果任何文件名包含換行符,則輸出的行數不是文件的數量。 – chepner