I wrote a shell script to check which ".err" text files are empty. Some files have a specific repeated phrase, like this example file fake_error.err (blank lines intentional):
WARNING: reaching max number of iterations
WARNING: reaching max number of iterations
WARNING: reaching max number of iterations
WARNING: reaching max number of iterations
WARNING: reaching max number of iterations
WARNING: reaching max number of iterations
WARNING: reaching max number of iterations
WARNING: reaching max number of iterations
WARNING: reaching max number of iterations
that I want to also remove in addition to the empty files. I wrote the following script to do so
#!/bin/bash
for file in *error.err; do
if [ ! -s $file ]
then
echo "$file is empty"
rm $file
else
# Get the unique, non-blank lines in the file, sorted and ignoring blank space
lines=$(grep -v "^$" "$file" | sort -bu "$file")
echo $lines
EXPECTED="WARNING: reaching max number of iterations"
echo $EXPECTED
if [ "$lines" = "$EXPECTED" ]
then
# Remove the file that only has iteration warnings
echo "Found reached max iterations!"
rm $file
fi
fi
done
However, the output of this script when run on the fake_error.err files is
WARNING: reaching max number of iterations
WARNING: reaching max number of iterations
from the two $echo statements in the loop, but the file itself is not deleted and the string "Found reached max iterations!" is not printed. I think the issue is in if [ "$lines" = "$EXPECTED" ] and I've tried using double brackets [[ ]] and == but none of those worked. I have no idea what the difference between the two printed statement are.
Why are the two variables not equal?
sort -buwon't delete them. e.g.echo ":$lines:"or something like that – ilkkachu Mar 29 '23 at 20:00: WARNING: reaching max number of iterations: WARNING: reaching max number of iterations. How can I remove the blanks from this? – m13op22 Mar 29 '23 at 20:24grep -qv -e '^$' -e 'WARNING: reaching max number of iterations'directly? – steeldriver Mar 29 '23 at 20:30if ! (grep -qv -e '^$' -e 'WARNING: reaching max number of iterations' $file)since it would return exit status 0 for matches found? – m13op22 Mar 29 '23 at 20:48wc -l "$file"andgrep -c '^[[:blank:]]*$' "$file". BTW, you can't combine an inverted match-vwith a normal match in the same grep command, the-vapplies to all-eoptions in that command. Use awk or perl if you need to do boolean logic with regex matches like! /^$/ && /WARNING: reaching.../. – cas Mar 30 '23 at 01:54awkinstead? – m13op22 Mar 30 '23 at 15:22! /^$/test is redundant, it's always going to be true if the line contains the warning. I just wanted a quick example and didn't think that one through. better would be if you wanted to check if a file contained both foo and bar on the same line, then you'd useawk '/foo/ && /bar/ { ... }'– cas Mar 30 '23 at 16:09