Dear all,
I have been trying to print an entire field, if the first line of the field is matching.
For example, my input looks something like this.
aaa ddd zzz
123 987 126
24 0.650 985
354 9864 0.32
0.333 4324 000
I am looking for a pattern, for example "ddd", which is in the second field and first row. Then I need to print the entire field, output should look like below.
ddd
987
0.650
9864
4324
How can I solve this by awk or sed?
Your help is appreciated.
CarloM
October 7, 2011, 6:47am
2
I imagine there are much neater ways, but this seems to work:
awk -vMYCOL="ddd" '{if (NR == 1) { for (i=1;i<=NF;i++) { if ($i == MYCOL) { mycolnum = i } } } { print $mycolnum }}' file1
EDIT: Changed a bit to output the header line.
Also, if there are no matching columns it just prints everything - if you want no output you'd need an additional if:
awk -vMYCOL="ddd" '{if (NR == 1) { for (i=1;i<=NF;i++) { if ($i == MYCOL) { mycolnum = i } } } { if (mycolnum) { print $mycolnum }}}' file1
1 Like
try this,
awk '{for(i=1;i<=NF;i++) {if(NR==1 && $i~/ddd/) {print $i;a=i;next}if(a>0){print $a;next}}}' filename
1 Like
If Perl is acceptable (this should handle multiple matching columns):
perl -lane'
$. == 1 and @f = grep $F[$_] =~ /ddd/, 0..@F;
@f and print join "\t", @F[@f]
' infile
pattern=ddd
awk -v p=$pattern 'NR==1{for(i=1;i<=NF;i++) if ($i~p) c=i}{print $c}' infile
awk -v var=ddd 'NR==1{for(i=0;++i<=NF;)if($i==var){_=i}}{$0=$_}1' file