jinfeng hu
jinfeng hu

Reputation: 5

awk-if with variables doesn't work properly sometimes

In a text, I want to classify my data according to it range.

For example, 8.1,9.1,9.9 are all in [8,10). I used variables called left and right to replace 8 and 10 respectively in awk-if. But it doesn't work properly.

My data like this:

9.1 aa
9.2 bb
10.1 cc
11.9 dd

Then my scripts like this:

left=8;right=10                    #left=10;right=12
echo "["$left","$right"]:"
cat data | awk '{if(($1>="'$left'")&&($1<"'$right'")) print $2}' | xargs

The result is empty.

[8,10]:

But if I use 8 and 10 directly (without variables), it's OK. And when I use left=10, right=12, it works also properly.

I also found when left=98, right=100, it also didn't work. So why sometimes it doesn't work? Thanks a lot!

Upvotes: 0

Views: 244

Answers (2)

Cyrus
Cyrus

Reputation: 88676

With awk's option -v:

left=8;right=10
awk -v l="$left" -v r="$right" '{if($1>=l&&$1<r) print $2}' data

or with environment variables:

export left=8 right=10
awk '{if($1>=ENVIRON["left"]&&$1<ENVIRON["right"]) print $2}' data

Output:

aa
bb

Upvotes: 2

jofel
jofel

Reputation: 3405

You are performing string comparison but want numeric comparison. Just swap the quotes:

 left=8;right=10 #left=10;right=12
 echo "["$left","$right"]:"
 cat data | awk '{if(($1>='"$left"')&&($1<'"$right"')) print $2}' | xargs

Upvotes: -1

Related Questions