Take the 2-minute tour ×

I am writing a gawk script that begins

#!/bin/gawk -f

I am calling the file via ./script file1.html but the script just returns nothing. Any ideas?

share|improve this question
add comment

3 Answers

up vote 6 down vote accepted

you can use ARGV[1] instead of FILENAME if you really want to use it in BEGIN block

awk 'BEGIN{print ARGV[1]}' file
share|improve this answer
That works if there is a file name - but doesn't print a dash if there isn't one (so the script is reading from standard input). –  Jonathan Leffler Mar 26 '11 at 17:05
@Jonathan, the question says, "I am calling the file via ./script file1.html" –  kurumi Mar 26 '11 at 21:46
+1, but with the warning that if you use this, you can't be using any command line arguments. So if ./script file1.html is the only way this is going to ever be run this is fine. If you ever add ./script --argument1ofn file1.html you're back to being screwed. –  JUST MY correct OPINION Mar 27 '11 at 2:48
Thanks for this! :D –  jonseager Mar 28 '11 at 8:30
add comment

Straight from the man page (slightly reformatted):

FILENAME: The name of the current input file. If no files are specified on the command line, the value of FILENAME is “-”. However, FILENAME is undefined inside the BEGIN block (unless set by getline).

share|improve this answer
add comment

You can print the file name when encounter line 1:

FNR == 1

If you want to be less cryptic, easier to understand:

FNR == 1 {print}


My first two solutions were incorrect. Thank you Dennis for pointing it out. His way is correct:

FNR == 1 {print FILENAME}
share|improve this answer
Either of those print the first record of the file. The correct way to use your technique for the OP's need: FNR == 1 {print FILENAME} (in other words, while your "less cryptic" would apply in the case of printing $0, it (and the variable name) are required in this case). +1 anyway –  Dennis Williamson Feb 9 '12 at 16:08
add comment

Your Answer


