awk Variables Command-line variable assignment

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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


Got any awk Question?