user1083096
user1083096

Reputation: 187

How do you grep a file and get the next 2 lines with a tab?

I could grep the lines containing the pattern "genes" and the next 2 consecutive lines using the following shell command from a text file.

grep -A 2 ' gene' file

output:

     gene            1..1515
                     /locus_tag="MSMEI_RS00005"
                     /old_locus_tag="MSMEI_0001"
     gene            2109..3302
                     /locus_tag="MSMEI_RS00010"
                     /old_locus_tag="MSMEI_0003"

now my aim is to print the consecutive lines with a tab like

gene            1..1515           /locus_tag="MSMEI_RS00005"   /old_locus_tag="MSMEI_0003"  
gene            2109..3302        /locus_tag="MSMEI_RS00010"   /old_locus_tag="MSMEI_0003"                  

how do I do this with the same grep command in shell?

Upvotes: 1

Views: 259

Answers (2)

ilkkachu
ilkkachu

Reputation: 6537

With sed:

sed -nEe '/^     gene/{N;N;s/\n */\t/g;p}' file

/ gene/ works on lines matching that pattern, then we read two Next lines, substitute newlines and following spaces with tabs, then print.

Upvotes: 2

Inian
Inian

Reputation: 85800

You don't need grep for it, Awk can do this manipulation using its getline() function to get the next two subsequent lines,

awk 'BEGIN{OFS="\t"}/gene/{getline n1; getline n2; print $0, n1,n2}' file

(or) if you are bothered with the leading spaces, strip them using gsub() function,

awk 'BEGIN{OFS="\t"}/gene/{gsub(/^[[:space:]]+/,"",$0); getline n1; getline n2; print $0, n1,n2}' file

Upvotes: 2

Related Questions