Reputation: 8115
If I use getline
in my awk script, it reads the next line from the stream and updates the $0 and NR variables (as it should). Is there a way to un-getline
?
For example, I want to use getline
to determine the EOF and then take an action on that. But if the condition is false (i.e., not EOF), then the script should continue normally.
#!/bin/gawk -f
{
print $0;
if (getline == 0)
{
print "EOF";
} else {
ungetline;
}
}
Without the ungetline
, the above script will only print every other input line.
One can wrap the whole script body with a while()
construct, but for this single use, it is just cleaner to undo the operation.
Upvotes: 4
Views: 1395
Reputation: 67507
Not sure that's the problem you're solving but for example, to print a line before the last line of the input you can follow "delaying printing" method. Here it's just printing the line but any processing can be similarly added.
$ seq 5 | awk 'NR>1 {print line}
{line=$0}
END {print "and finally..."; print line}'
1
2
3
4
and finally...
5
based on your updated posting, perhaps your use case is just the simulate the END
block.
$ seq 5 | awk '{print $1*$1}
END {print "EOF"}'
1
4
9
16
25
EOF
either you do something before the last line or after the last time; both cases are covered in these scripts. You can have a combination of these two as well. I'm still not sure about your use case...
Upvotes: 1