Search This Blog


Using Variables in Awk


When scripting it is likely that at some point you will run into a situation where you wish you could use a variable as a separator in awk. This can happen when you want a more "dynamic" field separator instead of the static (space_character) or any other standard character you choose.

The way to use variables in awk is simple but requires you to use a newer version of awk called 'nawk' or 'new awk'. I have tried with limited success to get this working in awk but it definitely not as flexible and as easy as nawk is.

Pulling variables from bash in order to use in awk is simple once you know how.

Here's how you do it: 

nawk -F "$bashVar0" '/match/ {print $1}' filetoparse.txt

  • -F "$bashVar0"
    • Using a value set in bash as a field separator for nawk
  • '/match/ {print $1}'
    • Matches a specific string and prints the first column after the initial field separator of -F "$bashVar0"

We can get a little more complicated by passing in multiple bash variables to match, and to use as field separators:

nawk -v NAWKVAR="$bashVar0" -F "$bashVar1" '$0 ~ toupper(NAWKVAR) && /match/ {print $1}' filetoparse.txt

  • -v
    • Allows for passing bash variables into awk. For example $bashVar0 is a variable that would have been set from an earlier command in your bash shell
  • NAWKVAR="$bashVar0"
    • Is setting a new variable name equal to the bash variable to use inside of nawk
  • -F "$bashVar1"
    • Using a value set in bash as a field separator for nawk
  • '$0 ~ toupper(NAWKVAR) && /match/ {print $1}'
    • Match all lines that have the upper-case variable passed into nawk. For the lines that match the variable passed into nawk also match a specific string and print the first column after the field separator of -F "$bashVar1"

No comments:

Post a Comment