gawk NR and match issues

Viewed 174

I need to use regexs to parse specific lines of a data file. My test command with match works, and my test command for specific line numbers work, but when I put them together, I get no output.

gawk 'NR==42 {print $0}' filename

prints out the entirety of line 42

gawk 'match($0, /([0-9]+)/, a) {print NR ":" a[1]}' filename

has a lot of print outs, but specifically has this output: 42:137674 So, my line 42 has a numeric match

gawk 'NR==42 match($0, /([0-9]+)/, a) {print NR ":" a[1]}' filename

doesn't print anything out, and I have no idea why.

I have a work around:

gawk 'match($0, /([0-9]+)/, a) {if (NR==42) print NR ":" a[1]}' filename

But I believe it's less performant, so would like to figure out why the other command doesn't work

EDIT: Answered, I totally forgot about && between the NR and match

1 Answers

Quick answer: The solution to the problem is adding the and-operator which was missing:

NR==42 && match($0, /([0-9]+)/, a) 
 

What happend in the OP?

Awk programs are generally written as a set of pattern-action pairs:

pattern { action }

which execute action when pattern is true.

The pattern used in the above reads:

NR==42 match($0, /([0-9]+)/, a)

which, due to the precedence order of the operators, actually resembles:

NR == (42  match($0, /([0-9]+)/, a))

Let us assume, for sake of example that we are on NR==42. The match function returns 0 or 1 depending whether or not a match is found. As mentioned in the OP, the match function returns 1 in case of NR==42. The pattern reads now:

42 == (42 1)

The operator of the form expr expr resembles string concatenation, so in awk, this is processed as

42 == ("42" "1")
42 == "421"

The operator == is a numeric operator if and only if both operands are numeric of nature. But "421" is a string, so it will convert the numeric value of NR to a string:

"42" == "421"

which is false and hence the action will not be executed.

note: the above action will execute if and only if the match function returns false on line 420 or true on line 421

Related