微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

检查文件是否为空

如何解决检查文件是否为空

我有一个没有任何数据的文件 需要检查以下场景并返回文件为空否则不为空

if file contains no data but as only spaces return it as FILE is EMPTY 
if file contains no data but as only tabs   return it as FILE is EMPTY
if file contains no data but as only empty new line  return it as FILE is EMPTY  

下面的代码能满足我上面的所有情况吗?或任何最好的方法一次性

if [ -s /d/dem.txt ]
then
    echo "FILE IS NOT EMPTY AS SOME DATA"
else
    echo "FILE IS EMPTY NOT DATA AVAILABLE"
fi 

解决方法

您可以使用此 awk

awk 'NF {exit 1}' file && echo "empty" || echo "not empty"

条件 NF 仅在文件中存在非空白字符时才成立。

,

您的描述有点不清楚(您想对包含空格、制表符和换行符的文件做什么?),但听起来您只想知道该文件是否包含任何非空白字符。所以:

 if grep -q '[^[:space:]]' "$file"; then
     printf "%s\n" "$file is not empty";
 else
     printf "%s\n" "$file contains only whitespace"
 fi
,

如果您运行过代码,您就会意识到不,-s 认为带有空格、制表符和/或换行符的文件不是空的。我会这样做:

myfile="some_file.txt"
T=$(sed -e 's/\s//g' "$i")
if [ -n "$T" ]; then
    echo "$i is NOT empty"
else
    echo "$i is empty"
fi

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。