Vijay
Vijay

Reputation: 985

Select column and print using awk

I am repeating the same example as in here. But the aspect of the question is different.

The example is as below.

#Frame  BMR_42@O22  BMR_49@O13  BMR_59@O13  BMR_23@O26  BMR_10@O13  BMR_61@O26  BMR_23@O25 
 1      1           1           0           1           1           1           1
 2      0           1           0           0           1           1           0
 3      1           1           1           0           0           1           1
 4      1           1           0           0           1           0           1
 5      0           0           0           0           0           0           0
 6      1           0           1           1           0           1           0
 7      1           1           1           1           0           0           0
 8      1           1           1           0           0           0           0
 9      1           1           1           1           1           1           1
10      0           0           0           0           0           0           0

I wanted to select only few columns with certain criteria and print them out.

Like I want to select only columns "BMR_*@O26" and print the whole columns. (note: the * is for any number)

So I tried with this command

awk '{for (i=2;i<=NF;i++) if ($i~/^BMR_[0-9]+@O26/) print }' inputFile.

Unfortunately, I don't get output as I wanted. The two columns that I wanted to print out are as below:

BMR_23@O26  BMR_61@O26 
1           1
0           1
0           1
0           0
0           0
1           1
1           0
0           0
1           1
0           0

How I could get the whole columns print out which I selected?

Many thanks in advance.

Upvotes: 0

Views: 228

Answers (1)

Ed Morton
Ed Morton

Reputation: 203349

You need to test the regexp on just the header line to get the field number and then print those field numbers for every line:

$ awk '
NR==1 { for (i=1;i<=NF;i++) if ($i ~ /BMR_.*@O26/) fld[++n] = i }
{ for (i=1;i<=n;i++) printf "%*s", (i<n?-12:1), $(fld[i]); print "" }
' file
BMR_23@O26  BMR_61@O26
1           1
0           1
0           1
0           0
0           0
1           1
1           0
0           0
1           1
0           0

Upvotes: 1

Related Questions