我有一个没有任何数据的文件 需要检查以下场景并返回文件为空否则不为空
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
答案 0 :(得分:4)
您可以使用此 awk
:
awk 'NF {exit 1}' file && echo "empty" || echo "not empty"
条件 NF
仅在文件中存在非空白字符时才成立。
答案 1 :(得分:4)
您的描述有点不清楚(您想对包含空格、制表符和换行符的文件做什么?),但听起来您只想知道该文件是否包含任何非空白字符。所以:
if grep -q '[^[:space:]]' "$file"; then
printf "%s\n" "$file is not empty";
else
printf "%s\n" "$file contains only whitespace"
fi
答案 2 :(得分:2)
如果您运行过代码,您就会意识到不,-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