11

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?

Bartzilla
  • 2,768
  • 4
  • 28
  • 37
jonseager
  • 317
  • 2
  • 8

4 Answers4

14

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

awk 'BEGIN{print ARGV[1]}' file
kurumi
  • 25,121
  • 5
  • 44
  • 52
  • 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
    +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 02:48
10

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}
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
  • 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 09 '12 at 16:08
  • This works for multiple files while accepted answer works only for first input file. This should be accepted answer. Good job ! +1 – Sergiy Kolodyazhnyy Jun 15 '15 at 14:44
7

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).

JUST MY correct OPINION
  • 35,674
  • 17
  • 77
  • 99
1

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 };
Warren Wright
  • 13
  • 1
  • 8