Govind Kumar
Govind Kumar

Reputation: 13

Why does if condition print zero value for non-zero condition?

I am unable to get the required output from bash code.

I have a text file:

1 0.00 0.00    
2 0.00 0.00    
3 0.00 0.08    
4 0.00 0.00    
5 0.04 0.00    
6 0.00 0.00    
7 -3.00 0.00 
8 0.00 0.00   

The required output should be only non-zero values:

0.08   
0.04   
-3.0

This is my code:

z=0.00
while read line
do
line_o="$line"
openx_de=`echo $line_o|awk -F' ' '{print $2,$3}'`   
IFS=' ' read -ra od <<< "$openx_de"
for i in "${od[@]}";do
if [ $i != $z ]
then
echo "openx_default_value is $i"
fi
done
done < /openx.txt

but it also gets the zero values.

Upvotes: 1

Views: 243

Answers (2)

Claes Wikner
Claes Wikner

Reputation: 1517

awk '{$1=""}{gsub(/0.00/,"")}NF{$1=$1;print}' file 
0.08
0.04
-3.00

Upvotes: 1

John1024
John1024

Reputation: 113864

To get only the nonzero values from columns 2 and 3, try:

$ awk '$2+0!=0{print $2} $3+0!=0{print $3}' openx.txt 
0.08
0.04
-3.00

How it works:

$2+0 != 0 {print $2} tests to see if the second column is nonzero. If it is nonzero, then the print statement is executed.

We want to do a numeric comparison between the second column, $2, and zero. To tell awk to treat $2 as a number, we first add zero to it and then we do the comparison.

The same is done for column 3.

Using column names

Consider this input file:

$ cat openx2.txt 
n  first  second
1  0.00   0.00
2  0.00   0.00
3  0.00   0.08
4  0.00   0.00
5  0.04   0.00
6  0.00   0.00
7 -3.00   0.00    8  0.00  0.00

To print the column name with each value found, try:

$ awk 'NR==1{two=$2; three=$3; next} $2+0!=0{print two,$2} $3+0!=0{print three,$3}' openx2.txt 
second 0.08
first 0.04
first -3.00

Upvotes: 1

Related Questions