问题描述
我有一个没有任何数据的文件 需要检查以下场景并返回文件为空否则不为空
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