DomainsFeatured DomainsFeatured - 2 months ago 6
Linux Question

Print Lines That Are Greater Than Two Fields

I'm okay with

grep
, but I know that
awk
is probably way more efficient in this case. I'm learning but not quite there yet.

I have some data:

record1,14.2,10,50
record2,10.7,5,-
record3,9.3,6.8,10
record4,8,2.7,10
record5,5.5,22.4,10
record6,3,23.6,55
record7,2.7,14.6,-


I would like to print only the lines that are greater than greater than 7 in field 3 and greater than 10 (while removing any dashs) in field 4. Thus, the output would be this:

record1,14.2,10,50
record6,3,23.6,55


I have played around using
awk '{print $3 > 7}'
, however, like i said, I'm not great with
awk
and conditions. I could do it with grep but I feel like that's inefficient. Any help is greatly appreciated.

Answer

The structure of an awk script is condition { action }. The default action is { print }, which prints the whole record.

  • Your conditions are $3 > 7 and $4 > 10.
  • Your field separator is a comma.

Combining those things we get:

awk -F, '$3 > 7 && $4 > 10' file