Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect EOF in awk?

Tags:

awk

eof

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

like image 681
user3562 Avatar asked Oct 29 '09 21:10

user3562


4 Answers

gawk implementation has special rule called ENDFILE which will be triggered after processing every file in argument list. This works:

awk '{line=$0} ENDFILE {print line}' files...

more details you can find here>>

like image 65
tworec Avatar answered Sep 22 '22 11:09

tworec


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" }'
like image 33
uriel Avatar answered Sep 18 '22 11:09

uriel


To detect the last line of each file in the argument list the following works nicely:

FNR == 1 || EOF {
  print "last line (" FILENAME "): " $0
}
like image 44
sgr Avatar answered Sep 20 '22 11:09

sgr


These are the only sensible ways to do what you want, in order of best to worst:

awk 'NR==FNR{max++; next} FNR == max { print "Final line:",$0 }' file file

awk -v max="$(wc -l < file)" 'FNR == max { print "Final line:",$0 }' file

awk 'BEGIN{ while ( (getline dummy < ARGV[1]) > 0) max++; close(ARGV[1])} FNR == max { print "Final line:",$0 }' file
like image 22
Ed Morton Avatar answered Sep 21 '22 11:09

Ed Morton