I try to run a one-line command like this
touch ./py.py; awk 'BEGIN{print FILENAME}' ./py.py
and expect to get the result ./py.py but only get a blank line. However, if I do it without a BEGIN block, it works:
touch ./py.py; awk '{print FILENAME}' ./py.py
It seems that the FILENAME variable is not available in the BEGIN block. Why is that? How can I use that variable in the BEGIN block?
Awk can process multiple files in one invocation (e.g.
awk '{whatever}' file1 file2 file3). The BEGIN block is executed when awk starts, before it opens the first file, not at the beginning of each file (END blocks are similar). One could possibly argue that extending awk to have per-file BEGIN/END hooks might be useful, but they don’t exist in any current version of awk/nawk/gawk that I’ve used…