foscolino
foscolino

Reputation: 81

bash check if all rows into files are equal to "number"

I have a file that contains some numbers (one per row) which are populated dynamically by another program, like this:

0
0
234
455
0

I should create a simple echo when ALL ROWS into file are equal to zero (0), I have created this script, but it does not work correctly:

if ! grep -x -q "0" "file";
then
echo "At least one row is not zero"
else
echo "All rows are zero"
fi

Upvotes: 0

Views: 827

Answers (2)

karakfa
karakfa

Reputation: 67547

with awk you can terminate as soon as you encounter non-zero. Might be important if file is large.

$ awk '$0!=0 {exit 1}' file

use the exit status

$ if awk '$0!=0 {exit 1}' file; then echo "all zeros"; else echo "nonzero"; fi

Upvotes: 1

Barmar
Barmar

Reputation: 782166

Use grep -v to search for any line that does not match the pattern.

if grep -q -v -x 0 filename
then echo At least one row is not zero
else echo All rows are zero
fi

Upvotes: 2

Related Questions