Using FILENAME in awk script

1.8k views Asked by At
#!/usr/bin/awk -f

{if(!FILENAME) {print "<Gasp.sh> <inputfile>"; exit} calc = 0;....}

I am trying to print out a usage statement in my awk script so if the script is run without an input file, it shows the usage. This is my attempt, but I assume I am not using the FILENAME variable correctly. I also tried putting the if statement in a BEGIN and END block but nothing has worked.

2

There are 2 answers

1
Ed Morton On BEST ANSWER
BEGIN{if (ARGC!=2) {print "<Gasp.sh> <inputfile>"; exit} {calc = 0;....}
0
James Brown On

Use ARGC instead;

BEGIN {
    if(ARGC==1) {
        print "<Gasp.sh> <inputfile>"
        exit
    } 
    calc = 0
    # ...
}

Edit: Unfortunately @shaikisiegal deleted his answer so I will add this quote from GNU awk documentation section Built-in Variables here:

FILENAME This is the name of the file that awk is currently reading. When no data files are listed on the command line, awk reads from the standard input, and FILENAME is set to "-". FILENAME is changed each time a new file is read (see section Reading Input Files). Inside a BEGIN rule, the value of FILENAME is "", since there are no input files being processed yet.

Some early implementations of Unix awk initialized FILENAME to "-", even if there were data files to be processed. This behavior was incorrect, and should not be relied upon in your programs.