GAWK Script - Print filename in BEGIN section
I am writing a gawk script that begins
#!/bin/gawk -f
BEGIN { print FILENAME }
I am calling the file via ./script file1.html
but the script just returns 开发者_如何转开发nothing. Any ideas?
you can use ARGV[1] instead of FILENAME if you really want to use it in BEGIN block
awk 'BEGIN{print ARGV[1]}' file
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}
UPDATE
My first two solutions were incorrect. Thank you Dennis for pointing it out. His way is correct:
FNR == 1 {print FILENAME}
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).
Building on Hai Vu's answer I suggest that if you only want the filename printed once per file it needs to be wrapped in a conditional.
if(FNR == 1) { print FILENAME };
精彩评论