检查文件是否为空
Check file empty or not
我的文件中没有任何数据
需要检查以下情况并且 return 文件为空否则不为空
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
仅当文件中有非空白字符时才为真。
如果您有 运行 您的代码,您会意识到不,-s
认为带有空格、制表符的文件 and/or 新行不是空的。我会这样做:
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
您的描述有点不清楚(您想对包含空格、制表符和换行符的文件做什么?),但听起来您只是想知道该文件是否包含任何非空白字符.所以:
if grep -q '[^[:space:]]' "$file"; then
printf "%s\n" "$file is not empty";
else
printf "%s\n" "$file contains only whitespace"
fi
我的文件中没有任何数据 需要检查以下情况并且 return 文件为空否则不为空
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
仅当文件中有非空白字符时才为真。
如果您有 运行 您的代码,您会意识到不,-s
认为带有空格、制表符的文件 and/or 新行不是空的。我会这样做:
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
您的描述有点不清楚(您想对包含空格、制表符和换行符的文件做什么?),但听起来您只是想知道该文件是否包含任何非空白字符.所以:
if grep -q '[^[:space:]]' "$file"; then
printf "%s\n" "$file is not empty";
else
printf "%s\n" "$file contains only whitespace"
fi