I've put together an example using the AWK getline
function and it's confusing me.
$ cat in
foo
bar
baz
$ awk '{ getline tmp; print tmp; print $0 }' in
bar
foo
bar
baz
I'm reading the next line into a variable named tmp
which doesn't change $0
as confirmed by the first two lines of output:
bar
foo
This is confirmed by the following table taken from The AWK Programming Language on page 62:
I know that the NR
and FNR
built-ins represent the number of lines read so far. I think this is the key to understanding what's going on but I'm confused how changing NR
while in a pass affects future passes.
I was expecting the next two lines to be:
baz
bar
because on the second pass $0 == bar
and tmp == baz
.
Then I was expecting the next two lines to really only be one line:
baz
because on the third pass $0 == baz
and tmp == null
.
So my expected output is:
bar
foo
baz
bar
baz
I think understanding how changing NR
while in the awk loop is the key to understanding this output.
- Can you explain why my expected output is wrong and why the actual output is right?
I'm running awk version 20070501
on macOS 10.12.1