How to detect EOF in awk?

user3562 picture user3562 · Oct 29, 2009 · Viewed 32.1k times · Source

Is there a way to determine whether the current line is the last line of the input stream?

Answer

uriel picture uriel · Oct 29, 2009

The special END pattern will match only after the end of all input. Note that this pattern can't be combined with any other pattern.

More useful is probably the getline pseudo-function which resets $0 to the next line and return 1, or in case of EOF return 0! Which I think is what you want.

For example:

awk '{ if(getline == 0) { print "Found EOF"} }'

If you are only processing one file, this would be equivalent:

awk 'END { print "Found EOF" }'