Extract data from records that match pattern

Hi Guys,

I have a file as follows:

a b c  1 2 3 4 
pp gg gh hh 1 2 fm 3 4 
g h i j k l m 1 2 3 4 
d e f g h j i  k l 1 2 3 f 3 4 
r t y u i o p d p re 1 2 3 f 4 
 
t y w e q w r a s p a 1 2 3 4 
 
 
 
 

I am trying to extract all the 2's from each row. 2 is just an example not a fixed number. The number of fields starting from the beginning of the each row are variable so I am trying to use the end of each row as the starting address to extract the 2 as the number of fields stay constant starting from the end of the row and moving backwards except some rows have an "f" or an "fm". When there is an "f" or an "fm" in the row, I want to extract the 3rd field from the end of the row (which will give me 2). When there is no "f" or "fm" in a row, I want to extract the 2nd field from the end of the row.

I also have blanks in the file and I want to extract those too. Does not matter which field I select for a blank line, any field will do as long as I get a blank.

Here is what I am trying:

 
awk 'if (/ f / || / fm /) {print $(NF - 2)}; else {print $(NF - 3)}' test.txt
 

It's giving me a syntax error on the else statement.

Also I know this won't work for a blank line as the NF will be zero.

Is there any easier way to do this?

Thanks.

awk '/^[ ]*$/ { print " "; next };/ f / || / fm / { print $(NF - 3); next }; { print $(NF - 2) }' test.txt
 nawk 'NF { print (/ f / || / fm /)?$(NF-2):$(NF-3)}' myFile

I'm not a nawk expert, but this stops processing after a blank/empty line.

I must admit tho, it's an interesting construction. I learned something.

No, it doesn't. For empty lines, the pattern (in this case the value of NF) will evaluate to a false value, and its associated action (the code inside the curly braces) will not be executed. AWK will then proceed to the next line and re-evalute the pattern, until it reaches the end of the file. An explicit exit statement would be needed to quit before EOF.

Regards,
Alister

On my Solaris 10 system it did stop executing after the blank line

Hi, sb008:

I'm not familiar with the Solaris userland, but that's odd and unexpected behavior, relative to every version of AWK that I've used over the past decade (nawk aka one true awk, gawk, mawk) and to the posix standard.

Regards,
Alister