grep for duration=N while N is longer than X, the position of this sentence changes between lines

Viewed 66

I have a very long file with a format of column_name=column_val, column_name2=column_val2 and so on.

the columns are not in the right order, lets say for example i have this file:

bar=x moshe=foo test=x duration=5
moshe=foo2 test=y duration=0 bar=y
duration=3 moshe=foo3 bar=z test=x

i want to return lines only where duration is greater then 2

as far as I know awk is not optional since i can't tell where the columns are location in each line.

on IRC in #bash channel someone recommended using gawk's match(). there too i was having problem seeing how to resolve this while each line the duration is elsewhere.

any ideas?

thanks

4 Answers

You can use duration= as field separator:

# showing field content in numeric context
$ awk -F'duration=' '{print +$2}' ip.txt
5
0
3

# use required numeric comparison to get desired output
$ awk -F'duration=' '+$2 > 2' ip.txt
bar=x moshe=foo test=x duration=5
duration=3 moshe=foo3 bar=z test=x

Note that if you have multiple duration= in a line, only the first one will be tested.

Extract the data with regex and compare.

awk '0+gensub(".*duration=([0-9]*).*", "\\1", "1") > 2'

@edit as above, the 0+ is needed to convert string to integer.

If you want to use grep:

grep -E 'duration=([3-9] |[0-9]{2,})' "file"
     awk '/duration/ {
         for (counter=1; counter <= NF; counter++) {
             if ($counter ~ /^duration*/) {
                 value=substr($counter, index($counter,"=")+1);
                 if (value > 2) {
                     print $0;
                 }
             }
         }
     }' <inputfile>
Related