bashawk

Specify other flags in awk script header


I want to write an awk script file using the #!/bin/awk -f header, but I want this script to always use : as a field separator. But for some reason writing #!/bin.awk -F: -f gives me a syntax error. I also want this script to always run on the same file, so I'd like to hardcode that as well. Basically, what I want to work is this:

#!/bin/awk -F: -f -- /etc/passwd

followed by some awk code


Solution

  • Many systems allow only a single argument in a shebang line, so everything after the space is passed as one argument.

    However, you can set FS and even ARGV in your script's BEGIN block, like this:

    #!/bin/awk -f              # using the #!/bin/awk -f
    BEGIN {
        FS=":"                 # always use : as a field separator
        ARGC=2
        ARGV[1]="/etc/passwd"  # always run on the same file
    }
    $3==0 {                    # followed by some awk code
        print $1
    }
    

    Run it:

    $ chmod u+x program.awk
    $ ./program.awk
    root