In Awk, are $_ and $0 synonyms?

Viewed 95

I find no reference to $_ in the Gnu Awk manual or the Wikipedia page, but I used it by mistake from a Perl habit and it seems to be identical to $0.

ping www.bbc.co.uk | awk '{print NR,$_}'
ping www.bbc.co.uk | awk '{print NR,$0}'

Is it some very old deprecated behaviour nobody's bothered to remove?

2 Answers

In OP's code:

ping www.bbc.co.uk | awk '{print NR,$_}'

Explanation: Above awk code its considering _ as a variable here, since no value is defined for variable _ so its value is zero(0) that's why it becomes from NR,$_ to NR,$0 and hence printing current line. So there is no special meaning for $_ unlike perl etc.

So even someone tries like: ping www.bbc.co.uk | awk '{print NR,$E}' also will print the samething.

You would get the same behaviour by using $any_undefined_variable instead of $_. The underscore is a valid variable name, and since the variable is undefined, its value in a numeric context defaults to zero, i.e., it is indeed equivalent to $0 but not because of $_ being a special case (which it isn't).

Related