Reputation: 717
I want to compare two alphanumeric strings and below is the bash expression I think should do the job. But I'm getting blank result. Please advise.
:~$ echo $tempnow $threshold
+60.0°C +80.0°C
:~$ res=`echo "$tempnow $threshold" | awk '{ if($1 > $2) print "Exceeds"; else echo "Normal" }'`
:~$ echo $res
:~$
Upvotes: 0
Views: 937
Reputation: 111
try below :-
res=`echo "$tempnow $threshold" | awk '{ if($1 > $2) print "Exceeds"; else print "Normal" }'`
Upvotes: 0
Reputation: 785721
There is no echo
in awk.
You can use:
echo '+90.0°C +80.0°C' | awk '{ print ($1+0 > $2+0 ? "Exceeds" : "Normal") }'
Exceeds
echo '+60.0°C +80.0°C' | awk '{ print ($1+0 > $2+0 ? "Exceeds" : "Normal") }'
Normal
Also note use of +0
to convert fields into numeric values.
Upvotes: 3
Reputation: 74685
You have written echo
instead of print
in your awk script.
This will be interpreted as the name of a function or variable, which doesn't exist, then it will be coerced to an empty string and concatenated with the string "Normal". The result will be discarded.
I would recommend writing your script as follows:
res=$(awk '{ print ($1 > $2 ? "Exceeds" : "Normal") }' <<<"$tempnow $threshold")
This uses <<<
to pass the string over standard input to awk. The result of the ternary operator is printed and stored in the variable $res
.
Bear in mind that you are currently comparing strings, so you will run into problems in situations such as this:
$ tempnow=+9.0°C
$ threshold=+80.0°C
$ awk '{ print ($1 > $2 ? "Exceeds" : "Normal") }' <<<"$tempnow $threshold"
Exceeds
Upvotes: 1