match pattern and print corresponding columns from a file using awk or grep
<p>I have a input file with repetitive headers (below):</p>

<pre><code>A1BG A1BG A1CF A1CF A2ML1
aa bb cc dd ee
1 2 3 4 5
</code></pre>

<p>I want to print all columns with same header in one file. e.g for above file there should be three output files; 1 for A1BG with 2 columns; 2nd for A1CF with 2 columns; 3rd for A2ML1 with 1 column. I there any way to do it using one-liners by awk or grep?</p>

<p>I tried following one-liner:</p>

<pre><code>awk -v f="A1BG" '!o{for(x=1;x&lt;=NF;x++)if($x==f){o=1;next}}o{print $x}' trial.txt
</code></pre>

<p>but this searches the pattern in only one column (1 in this case). I want to look through all the header names and print all the corresponding columns which have A1BG in their header.</p>