Justin Lok
Justin Lok

Reputation: 1270

Using awk with variable

I am using this awk command to extract three rows from a text file.

awk 'BEGIN {FS="\t";OFS=","}; {print $1,$3,$10}' $FILENAME > $OUTPUT

I wish to specify the column numbers as a variable separately so it will be easier to modify in the future like this:

COLUMNS=$1,$3,$10
awk 'BEGIN {FS="\t";OFS=","}; {print $COLUMNS}' $FILENAME > $OUTPUT

However it pulls all columns into the output, not only the 3 I specified. How do I do this properly?

Upvotes: 1

Views: 56

Answers (1)

bian
bian

Reputation: 1456

like this ?

$ more file
a,b,c,d,e
1,2,3,4,5

$ a='$1,$2,$NF'

$ awk -F, "{print $a}" file
a b e
1 2 5

Upvotes: 1

Related Questions