Shell – Passing print pattern as a variable to awk

awkkshshell

I am trying to use awk to print variables from various columns in a line delimited by , .The columns and pattern which I want to print is stored in another variable b.
The pattern a and print patter b are given below:

a='15986327,415532694,850257614,875121642,20140819'
b='$1","$2","$4'

I am trying to get the output as below.

15986327,415532694,875121642

I am trying to pass the pattern b to awk using -v switch but not sure how to use that with print inside awk. Tried below commands but this is not the output I was trying to get to.

echo $a |awk -v ba="${b}" -F"," '{print ba}'
$1","$2","$4

echo $a |awk -v ba="${b}" -F"," '{print $ba}'
15986327,415532694,850257614,875121642,20140819

Best Answer

You don't need to use variable ba, try:

$ echo $a | awk -F',' '{print '"$b"'}'
15986327,415532694,875121642

With this, $b is expanded by the shell, not by awk. And the rest of awk statement is not affect, because they're enclosed in single quote.

Related Question