arnpry
arnpry

Reputation: 1141

Print Entire Column Based on Header Match

I am trying to match a header in CSV file I am working with, followed by printing the entire column.

some.file:

col_1,col_2,col_3,col_4,col_5
2333,4345,365678,54356,34443

Code:

awk -F, 'NR==1{for(i=1;i<=NF;i++){if($i=="col_3")x=i;}} NR>1{if($x=="1")print;}' some.file

When I run this however, I get a blank return...

Upvotes: 0

Views: 284

Answers (1)

sat
sat

Reputation: 14949

You can use this awk:

awk -F',' -v search="col_3" 'NR==1{for(i=1;i<=NF;i++){ if ($i == search) c=i } } c{print $c}' file

Output:

col_3
365678

You can pass required column name to awk by using search variable.

From your example:

awk -F, 'NR==1{for(i=1;i<=NF;i++){if($i=="col_3")x=i;}} x!=0{print $x}' file

Upvotes: 2

Related Questions