awk: Built-in FILENAME variable on empty file
From the awk
manual:
FILENAME A pathname of the current input file.
Inside a BEGIN action the value is undefined. (...)
I think this is the explanation. Until a field is processed the value of FILENAME
is undefined. Since no field is processed in case of an empty file the variable stays uninitialised.
Note: parts of this answer are specific to GNU awk
, specifically 4.0 and later, which added BEGINFILE
/ENDFILE
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.
awk 'BEGINFILE{print "File name: " FILENAME}' myfile
If supported, this will print File name: myfile
once, before processing any lines. (Otherwise it will probably decide that BEGINFILE
is variable with a false value, and print nothing at all.)
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:
.