Shell – Passing arguments to awk script

awkshellshell-script

I have a awk script where i want to be able to pass N arguments into it and also read from stdin. I would like to be able to do something like

tail -f logfile | my_cool_awk_scipt var1 var2 var3 ... varN

And then use these variables inside the script.

#!/bin/awk -f

BEGIN { 
print "AWK Script Starting" 
print ARGV[1]
}                                                                              
{
    if ($0 < ARGV[1])
        print $0
    else if ($0 < ARGV[2])
        print $0 + ARGV[2]             
}
  

If i try to pass the variables as it stands it print ARGV[1] and then hits

awk: ./my_cool_awk_script:4: fatal: cannot open file `var1' for reading (No such file or directory)

I can do,

tail -f logfile | my_cool_awk_scipt -v var1=var1 -v var2=var2 -v var3=var3 ... varN=varN

but this is a bit limiting and verbose. I know I can also wrap this in a shell script but am unsure a clean way to embed what I have into something like that.

Best Answer

The moment awk hits the main body of the script, after BEGIN, it's going to want to read the filenames specified in ARGV[x]. So just nuke 'em.

$ cat a.awk
#!/bin/awk -f
BEGIN {
print "AWK Script Starting"
ZARGV[1]=ARGV[1]
ZARGV[2]=ARGV[2]
ARGV[1]=""
ARGV[2]=""
}
{
    if ($0 < ZARGV[1])
        print $0
    else if ($0 < ZARGV[2])
        print $0 + ZARGV[2]
}
$

Example:

$ cat logfile
1
2
3
4
5
$ ./a.awk 3 4 <logfile
AWK Script Starting
1
2
7
$
Related Question