To assign variables from the command-line, -v
can be used:
$ awk -v myvar="hello" 'BEGIN {print myvar}'
hello
Note that there are no spaces around the equal sign.
This allows to use shell variables:
$ shell_var="hello"
$ awk -v myvar="$shell_var" 'BEGIN {print myvar}'
hello
Also, this allows to set built-in variables that control awk
:
See an example with FS
(field separator):
$ cat file
1,2;3,4
$ awk -v FS="," '{print $2}' file
2;3
$ awk -v FS=";" '{print $2}' file
3,4
Or with OFS
(output field separator):
$ echo "2 3" | awk -v OFS="--" '{print $1, $2}'
2--3
$ echo "2 3" | awk -v OFS="+" '{print $1, $2}'
2+3