bash Unix 验证文件有无内容和空行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17980344/
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
Unix to verify file has no content and empty lines
提问by iaav
How to verify that a file has absolutely no content. [ -s $file ] gives if file is zero bytes but how to know if file is absolutely empty with no data that including empty lines ?
如何验证文件绝对没有内容。[ -s $file ] 给出文件是否为零字节,但如何知道文件是否绝对为空且没有包含空行的数据?
$cat sample.text
$ ls -lrt sample.text
-rw-r--r-- 1 testuser userstest 1 Jul 31 16:38 sample.text
When i "vi" the file the bottom has this - "sample.text" 1L, 1C
When i "vi" the file the bottom has this - "sample.text" 1L, 1C
采纳答案by anubhava
Your file might have new line character only.
您的文件可能只有换行符。
Try this check:
试试这个检查:
[[ $(tr -d "\r\n" < file|wc -c) -eq 0 ]] && echo "File has no content"
回答by jblack
A file of 0 size by definition has nothing in it, so you are good to go. However, you probably want to use:
根据定义,大小为 0 的文件中没有任何内容,因此您可以开始使用了。但是,您可能想要使用:
if [ \! -s f ]; then echo "0 Sized and completely empty"; fi
Have fun!
玩得开心!
回答by Gert van den Berg
Blank lines add data to the file and will therefore increase the file size, which means that just checking whether the file is 0 bytes is sufficient.
空行会向文件中添加数据,因此会增加文件大小,这意味着只需检查文件是否为 0 字节就足够了。
For a single file, the methods using the bash built-in -s
(for test
, [
or [[
). ([[
makes dealing with !
less horrible, but is bash-specific)
单个文件,使用的是bash方法内置-s
(用于test
,[
或[[
)。([[
使处理!
不那么可怕,但特定于 bash)
fn="file"
if [[ -f "$fn" && ! -s "$fn" ]]; then # -f is needed since -s will return false on missing files as well
echo "File '$fn' is empty"
fi
A (more) POSIX shell compatible way: (The escaping of exclamation marks can be shell dependant)
A (more) POSIX shell 兼容方式:(感叹号的转义可以依赖于shell)
fn="file"
if test -f "$fn" && test \! -s "$fn"; then
echo "File '$fn' is empty"
fi
For multiple files, find is a better method.
对于多个文件,find 是更好的方法。
For a single file you can do: (It will print the filename if empty)
对于单个文件,您可以执行以下操作:(如果为空,它将打印文件名)
find "$PWD" -maxdepth 1 -type f -name 'file' -size 0 -print
for multiple files, matching the glob glob*
:(It will print the filenames if empty)
对于多个文件,匹配 glob glob*
:(如果为空,它将打印文件名)
find "$PWD" -maxdepth 1 -type f -name 'glob*' -size 0 -print
To allow subdirectories:
允许子目录:
find "$PWD" -type f -name 'glob*' -size 0 -print
Some find
implementations does not require a directory as the first parameter (some do, like the Solaris one). On most implementations, the -print
parameter can be omitted, if it is not specified, find
defaults to printing matching files.
有些find
实现不需要目录作为第一个参数(有些需要,比如 Solaris 的)。在大多数实现中,该-print
参数可以省略,如果未指定,则find
默认打印匹配文件。