3

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
5

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.

1

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:

a='15986327,415532694,850257614,875121642,20140819'
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.