how to print variables after each file with awk

Viewed 73

Expanding on Print the last line of a file, from the CLI

I'm calling awk and passing * to process all files in the folder, but can't seem to figure out how to dump my variables after each file.

  • The END keyword seems to run only after all files have completed:
    • awk -F"'" '/export const/ { print $0 } END { print "done" }' *
    • awk -F"'" '/export const/ { CLSNM = $0 } END {print CLSNM }' *
  • And these don't fire at all (no output):
    • awk -F"'" '/export const/ { CLSNM = $0 } NR==filesize { print CLSNM }' *
    • awk -F"'" '/export const/ { CLSNM = $0 } NR==LNR { print CLSNM }' *

I'm on MacOS using GNU Awk 5.1.0, API: 3.0 (GNU MPFR 4.1.0, GNU MP 6.2.1)

1 Answers

Action you are looking to be done should be covered with ENDFILE, try following code once. This is a GNU awk option, should work for your shown versioned of awk.

awk -F"'" '/export const/ { CLSNM = $0 } ENDFILE{ print CLSNM;CLSNM="" }' *

2nd solution: without EBNDFILE option try following, should work with any awk version.

awk -F"'" 'FNR==1 && CLSNM{ print CLSNM; CLSNM=""} /export const/ { CLSNM = $0 } END{if(CLSNM){print CLSNM}}' *
Related