Passing Parameters Into a Script

One of the more confusing subtleties of programming in awk is passing parameters into a script. A parameter assigns a value to a variable that can be accessed within the awk script. The variable can be set on the command line, after the script and before the filename.

awk 'script' var=value inputfile

Each parameter must be interpreted as a single argument. Therefore, spaces are not permitted on either side of the equal sign. Multiple parameters can be passed this way. For instance, if you wanted to define the variables high and low from the command line, you could invoke awk as follows:

$ awk -f scriptfile high=100 low=60 datafile

Inside the script, these two variables are available and can be accessed as any awk variable. If you were to put this script in a shell script wrapper, then you could pass the shell’s command-line arguments as values. (The shell makes available command-line arguments in the positional variables—$1 for the first parameter, $2 for the second, and so on.)[14] For instance, look at the shell script version of the previous command:

awk -f scriptfile "high=$1" "low=$2" datafile

If this shell script were named awket, it could be invoked as:

$ awket 100 60

“100” would be $1 and passed as the value assigned to the variable high.

In addition, environment variables or the output of a command can be passed as the value of a variable. Here are two examples:

awk '{ ... }' directory=$cwd file1 ...
awk '{ ... }' directory=`pwd` file1 ...

“$cwd” ...

Get sed & awk, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.