Hopelessone
Hopelessone

Reputation: 337

How to make monetary field greater than & less than value in AWK?

I have the following:

field:field:field:$90.00:field
field:field:field:$85.00:field

I'm trying to make field $4 greater than or = to 90, and less than 100, however, I got my awk statement wrong somewhere and I cant figure out where and why its wrong.

awk -F: '{gsub("\$","",$4); if ($4 >= 90 && $4 < 100) print $1 ":" $2 " " $4 }' file.txt > output.txt

I tried to remove the $ sign to make it more like an integer, How to fix this?

Upvotes: 0

Views: 240

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74695

Use sub, as you're only looking to perform a single substitution, not a global one. Also, use a regular expression literal, rather than a string, which is first parsed by awk and as such, requires double-escaping:

sub(/\$/, "", $4)

Optionally you could add an anchor to the start of the field /^\$/.

Personally, I think it's nicer to use commas in your print command to insert the Output Field Separator (a space by default).

Also, remember that the structure of an awk program is condition { action } so often, you don't need to write an if.

Combining all that:

awk -F: '{ sub(/\$/, "", $4) } ($4+0) >= 90 && ($4+0) < 100 { print $1":"$2, $4 }' file.txt > output.txt

Arguably you could make the sub part of the condition as it will return 1 (true) when it makes a substitution but I don't think there's much of an advantage to doing so.

Note that I have added 0 to the field to make sure that a numerical comparison is performed. The reason for this is given in the GNU awk manual:

A string constant or the result of a string operation has the string attribute.

Upvotes: 1

P....
P....

Reputation: 18411

echo "$x" | awk -F: '{gsub("\\$","",$4); if ($4 >= 90 && $4 < 100) print $1 ":" $2 " " $4 }'
field:field 90.00

double escape dollar sign.

Upvotes: 1

Related Questions