To demonstrate the requirement, lets say we had a data file with 5 columns like so:
data_file.txt
A1 B1 C1 D1 E1
A2 B2 C2 D2 E2
A3 B3 C3 D3 E3
...
To start lets say you knew you wanted to extract the first and third column. Then your awk command would look something like this:
Script
awk '{printf "%s\t%s\n", $1, $3}' < data_file.txt
That is very straight forward and works, but lets say now that for various reasons you didn't know which columns you needed to extract ahead of time (or wanted to make your script more flexible). The obvious thing to do here is to define which columns you were interested in as a script variable like so...
Script
MY_COL1=1
MY_COL2=3
...
How do you use these with awk though? For example the following: `awk '{printf "%s\t%s\n", $$MY_COL1, $$MY_COL2}' < data_file.txt` will fail with this error:
Error
awk: illegal field $(), name "MY_COL1"
input record number 1, file
source line number 1
The answer is to use awk's -v parameter to assign variables in awk to tell it which column numbers we're interested in. So assuming the above variables have been assigned with the column numbers we want, the following script will do the trick:
Script
MY_COL1=1
MY_COL2=3
awk -v c1=$MY_COL1 -v c2=$MY_COL2 '{printf "%s\t%s\n", $c1, $c2}' < data_file.txt
Note how the $1 and $3 in the original awk program are now $c1 and $c2 respectively and both of c1 and c2 variables are assigned values from the shell script variables using the -v parameter.
So now you can redefine which columns are extracted by changing the shell script variable while leaving the awk command alone.
-i