Pass Bash Variables to Awk

Bash variables can’t be passed into awk, like one can with a lot of other commands. They need to be declared using the -v option. Here’s a code snippet which shows how.

#!/bin/bash
mainstring="abcdef"
substring="cde"
awk -v a="$mainstring" -v b="$substring" 'BEGIN  { print index(a,b) }'

The above awk command is for locating the position of the first letter of the substring cde within the main string abcdef. In this case the position is 3, which is the position of the character ‘c’ in the main string. The variables $mainstring and $substring are passed into awk by pre-declaring them as a and b respectively.