if condition not evaluating as expected

Hi all,

Thanks in advance for your time.

I have a data file like this:

1 7.465753425
2 8.980821918
1 1.717808219
1 6.550684932
0 5.432876712

I wish to write a bash script to check both columns and output a 1 if col1==1 AND col2<3. Otherwise I want to output a 0. In the above example, the result would be:

0
0
1
0
0

My script:

inputfile=events
outputfile=surv3yrs

while read line
do

type= echo $line | awk '{print $1}'
time= echo $line | awk '{print $2}'

echo $type
echo $time

if [[ $type -eq 1 && $time -lt 3 ]]; then
	echo 1 >> $outputfile
else 
	echo 0 >> $outputfile
fi

done < $inputfile

The echo $type and echo $time statements are in there to ensure the file is read correctly, which it seems to be. However my results are all 0s:

0
0
0
0
0

So my condition statement is never evaluating to true. Can anyone explain why?

Also if there's a better solution to this problem I'd be glad to here it - output can be in another file (as above) or recoded into another column of the same file, I don't really care.

Many thanks,
Jen

hi ,
Something like this ?

 awk '{if ($1==1 && $2 < 3) { print "1"} else {print "0"}}' inputfile
1 Like
$ awk '{print ($1==1&&$2<3)?1:0}' $inputfile
0
0
1
0
0

Here's an updated version of your script:

while read type time rest_of_line
do

echo $type
echo $time

if [[ $type -eq 1 && $time -lt 3 ]]; then
        echo 1 >> $outputfile
else
        echo 0 >> $outputfile
fi

done < $inputfile

Many thanks to both of you for your solutions.

awk '{print ($1==1&&$2<3)?1:0}' $inputfile

Works a treat, and is much simpler - thank you scottn.

The re-worked code you posted gives me many similar error messages:

./convertevents.sh: line 16: [[: 7.465753425: syntax error: invalid arithmetic operator (error token is ".465753425")

I don't think it's reading the real number (7.465....) properly. Any thoughts? I'll be using the simpler awk code but I'd like to understand the read line function as well, for future reference.

Cheers.

Hi.

What shell are you using, on what OS?

Try this, but going by the error, it's probably much the same:

if [ $type -eq 1 -a $time -lt 3 ]; then

Shells don't usually handle floating point arithmetic (the number will get truncated), which makes your if problematic.

$ a=3.3
$ b=3.2
$ [ $a -gt $b ] && echo a is greater than b
$ (no output)

bash, Mac OS 10.5

It's fine, I think understand the problem now, and I don't need to get this particular code working anyway as I've used the more elegant awk solution.

Thanks for your help.