Note: parts of this answer are specific to GNU awk
, specifically 4.0 and later, which added BEGINFILE
/ENDFILE
Per-line block
awk '{print "File name: " FILENAME}' myfile
This will print File name: myfile
once for every line in myfile. If myfile is a blank file (zero bytes), it will contain no lines, and so the above string won't be printed at all.
BEGINFILE
block
awk 'BEGINFILE{print "File name: " FILENAME}' myfile
If supported, this will print File name: myfile
once, before processing any lines.
Otherwise, if not supported, it will probably treat BEGINFILE
as a falsy conditional expression, and print nothing at all.
BEGIN
block
awk 'BEGIN{print "File name: " FILENAME}' myfile
This block is evaluated happens before the any of the files are processed, and at this time the value of FILENAME
is not defined.
The gawk
documentation specifically defines it as ""
though, so we can know there it will just print File name:
.