From the sample input:

cat file.txt
ID1    sample1    sample2    match1    sample3
ID2    sample4    match2     matchABC   

I would like to obtain sample output, keeping only the matched words on the same line. In this case, I want to keep the ID* and the match*

cat file.txt
ID1    match1
ID2    match2     matchABC  

Things I tried:

cat file.txt | awk '{for(i=1;i<=NF;i++){if($i~/^match|ID/){print $i}}}'

I get the wanted match but not in the correct format (they're all in separate lines of the output). I tried grep with option -o and multiple patterns but the match is also printed on separate lines, as expected behaviour.

2 Answers 2


Assuming you don't REALLY want to have to match explicitly on ID but rather just want the first field printed when there's any other field that matches match:

$ awk '{c=0; for (i=2;i<=NF;i++) if ($i ~ /^match/) printf "%s%s%s", (c++ ? "" : $1), OFS, $i} c{print ""}' file
ID1 match1
ID2 match2 matchABC

Try also

awk '{for (i=1; i<=NF; i++) if ($i !~ /match|ID/) $i=""} 1' file1
ID1   match1 
ID2  match2 matchABC

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .