Reputation: 995
I have file which does not have any data in it Need to check below scenario and return file is empty otherwise not empty
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
Does this below code will satisfy all my above cases ? or any best approach all in one go
if [ -s /d/dem.txt ]
then
echo "FILE IS NOT EMPTY AS SOME DATA"
else
echo "FILE IS EMPTY NOT DATA AVAILABLE"
fi
Upvotes: 3
Views: 2723
Reputation: 212238
Your description is a bit unclear (what do you want to do with a file that contains spaces, tabs, and newlines?), but it sounds like you just want to know if the file contains any non-whitespace characters. So:
if grep -q '[^[:space:]]' "$file"; then
printf "%s\n" "$file is not empty";
else
printf "%s\n" "$file contains only whitespace"
fi
Upvotes: 5
Reputation: 195
If you had run your code you would have realized that no, -s
considers that files with spaces, tabs and/or new lines are not empty. I would do it like this:
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
Upvotes: 2
Reputation: 785058
You may use this awk
for this:
awk 'NF {exit 1}' file && echo "empty" || echo "not empty"
Condition NF
will be true only if there is non-whitespace character in the file.
Upvotes: 5