Linux 查找目录和子目录中的所有零字节文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15703664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find all zero-byte files in directory and subdirectories
提问by Civa
How can I find all zero-byte files in a directory and its subdirectories?
如何在目录及其子目录中找到所有零字节文件?
I have done this:
我已经这样做了:
#!/bin/bash
lns=`vdir -R *.* $dir| awk '{print "\t"}'`
temp=""
for file in $lns; do
if test $file = "0"; then
printf $temp"\t"$file"\n"
fi
temp=$file
done
But, I only get results in the current directory, not subdirs, and if any file name contains a space then I get only first word followed by tab
但是,我只在当前目录中得到结果,而不是在子目录中,如果任何文件名包含空格,那么我只得到第一个单词,然后是制表符
采纳答案by William Pursell
To print the names of all files in and below $dir of size 0:
要打印大小为 0 的 $dir 中及以下的所有文件的名称:
find "$dir" -size 0
Note that not all implementations of find
will produce output by default, so you may need to do:
请注意,并非所有实现find
都会默认产生输出,因此您可能需要执行以下操作:
find "$dir" -size 0 -print
Two comments on the final loop in the question:
关于问题中最后一个循环的两条评论:
Rather than iterating over every other word in a string and seeing if the alternate values are zero, you can partially eliminate the issue you're having with whitespace by iterating over lines. eg:
与其遍历字符串中的所有其他单词并查看替代值是否为零,您可以通过遍历行来部分消除空白问题。例如:
printf '1 f1\n0 f 2\n10 f3\n' | while read size path; do
test "$size" -eq 0 && echo "$path"; done
Note that this will fail in your case if any of the paths output by ls contain newlines, and this reinforces 2 points: don't parse ls
, and have a sane naming policy that doesn't allow whitespace in paths.
请注意,如果 ls 输出的任何路径包含换行符,这将在您的情况下失败,这加强了 2 点:不要 parse ls
,并且具有不允许路径中有空格的合理命名策略。
Secondly, to output the data from the loop, there is no need to store the output in a variable just to echo
it. If you simply let the loop write its output to stdout, you accomplish the same thing but avoid storing it.
其次,要从循环中输出数据,无需将输出存储在变量中echo
。如果您只是让循环将其输出写入 stdout,您可以完成相同的操作,但避免存储它。
回答by Batcher
No, you don't have to bother grep.
不,您不必费心 grep。
find $dir -size 0 ! -name "*.xml"
回答by LinuxLuigi
As addition to the answers above:
除了上面的答案:
If you would like to delete those files
如果您想删除这些文件
find $dir -size 0 -type f -delete
回答by Mike Q
Bash 4+ tested - This is the correct way to search for size 0:
Bash 4+ 测试 - 这是搜索大小 0 的正确方法:
find /path/to/dir -size 0 -type f -name "*.xml"
Search for multiple file extensions of size 0:
搜索大小为 0 的多个文件扩展名:
find /path/to/dir -size 0 -type f \( -iname \*.css -o -iname \*.js \)
Note: If you removed the \( ... \) the results would be all of the files that meet this requirement hence ignoring the size 0.
注意:如果删除 \( ... \) 结果将是满足此要求的所有文件,因此忽略大小 0。