你的主要错误是你是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