wooden wooden - 8 months ago 40
Bash Question

If statement in awk works not as predicted

My second column values are starting from 0 to 2000, and variable $a is set to be 13. If statement in awk does not work as it supposed to it... it prints all values. Code:

IFS=- read a b <<< "$1"
echo $a # value is displayed as 13
echo $b # value is displayed as 20... for now it does not matter
sort -r -k 2,2 $2 | awk '{if ($2 > $a) print $2}' # if statement should check which of a second column values are greater than 13, and print them

Everything is okay when I compare my second column like this (putting 13 instead of $a):

sort -r -k 2,2 $2 | awk '{if ($2 > 13) print $2}'

So my thought is that I put $a in If statement wrong


That's because shell variables will not get expanded withing single quotes.

awk has a handy mechanism to set awk variables:

awk -v value="$a" '{if ($2 > value) print $2}'

which can be written more "awkishly" as

awk -v value="$a" '$2 > value {print $2}'