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:


I am trying to get the output as below.


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}'

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

2 Answers 2


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

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

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.


awk variables are just used for their values, like variables in most languages - they aren't re-parsed for expressions. You can do what you want with this:

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

(setting OFS so you get commas in the output). If having b as a variable is required, you can use:

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

instead, which substitutes b in as part of the awk expression.

All of that said, you don't need awk for this. This is really a job for cut:

echo "$a" | cut -d, -f1,2,4

That selects fields 1, 2, and 4, using , as a field delimiter, with no complex double parsing of code. This is exactly what cut is made for.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .