Advertisement
devinteske

awk BEGINFILE/ENDFILE without GNU awk

Nov 18th, 2014
1,174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Awk 0.59 KB | None | 0 0
  1. #
  2. # Like GNU awk's BEGINFILE/ENDFILE but works with any awk(1)
  3. # NB: Named beginfile()/endfile() to prevent conflict with GNU awk
  4. #
  5. function beginfile(file) {
  6.     numlines = FNR == 0 ? 0 : 1 # to simulate `wc -l'
  7. }
  8. function endfile(file) {
  9.     printf "%8u %s\n", numlines, file # to simulate `wc -l'
  10. }
  11. { numlines++ } # to simulate `wc -l'
  12. # Cross-platform compatible implementation of GNU awk's BEGINFILE/ENDFILE
  13. NR == 1 { beginfile(file = FILENAME) }
  14. FNR != NR {
  15.     FNR = NR
  16.     endfile(file)
  17.     beginfile(file = FILENAME)
  18. }
  19. END {
  20.     endfile(file)
  21.     printf "%8u total\n", FNR # to simulate `wc -l'
  22. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement