Skip to content
Advertisement

How to pass “-L” to an awk script?

I am trying to write an awk script that accepts -L as an argument.

As an example to show you what I want, here is a simple awk script called awktest:

#!/usr/bin/awk -f 
BEGIN 
{
   print ARGV[1]
}

If I run this from shell:

$./awktest -w

I get as output:

-w

Which is what I expect. It seems to work for anything I put in except -L.

If I run:

$./awktest -L

I get:

awk: option requires an argument --L

When I am expecting ARGV[1] to just contain -L. What is going on here? Why does it fail on this specific case and how can I make it accept -L in ARGV? Thanks

Advertisement

Answer

Wrap your awk script in a shell script:

#!/bin/sh
awk 'BEGIN {
      print ARGV[1]
     }' "$@"

Example:

$ ./awktest -L
-L

The problem is that when running a script with a shebang line, the specified program is run with the name of the script and the script’s arguments as extra command line arguments. In other words, with your original awktest script, running awktest -L turns into /usr/bin/awk -f /path/to/awktest -L, thus awk treats the -L as an argument to it, and not to the actual script.

If you don’t want to use the ./awktest -- -L syntax, you need another layer of indirection to put the script arguments where they need to be.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement