1

I have a file like this

SRR959756.1081725       1       RNU2-54P:112:133:hsa-miR-1246
SRR959756.1162547       1       RNU2-54P:112:133:hsa-miR-1246
SRR959756.128602        2       RNU2-37P:85:108:hsa-miR-877-3p  RNU2-59P:99:122:hsa-miR-877-3p

This is a tab separated file where I want the result like this

SRR959756.1081725       1       RNU2-54P:112:133:hsa-miR-1246
SRR959756.1162547       1       RNU2-54P:112:133:hsa-miR-1246
SRR959756.128602        2       RNU2-37P:85:108:hsa-miR-877-3p  
SRR959756.128602        2       RNU2-59P:99:122:hsa-miR-877-3p

So like in 3rd line I have 3rd and 4th columns. But 1st and 2nd column should always be printed and then 3rd column, then in the next line 1st and 2nd column and then 4th column.

How can i do this in awk

2
$ awk -v OFS='\t' '{for (i=3;i<=NF;i++)print $1,$2,$i}' file
SRR959756.1081725       1       RNU2-54P:112:133:hsa-miR-1246
SRR959756.1162547       1       RNU2-54P:112:133:hsa-miR-1246
SRR959756.128602        2       RNU2-37P:85:108:hsa-miR-877-3p
SRR959756.128602        2       RNU2-59P:99:122:hsa-miR-877-3p

How it works

  • -v OFS='\t'

    This sets the output field separator, AKA OFS, to a tab.

  • for (i=3;i<=NF;i++) print $1,$2,$i

    This runs a loop starting with column 3 and all columns after and prints them on a line preceded by columns 1 and 2.

1
awk '{print $1,$2,$3}$4{print $1,$2,$4}'

==

awk '{print $1,$2,$3;$3="\b"}$4'

or

awk -v OFS="\t" '$4{$4="\n"$1"\t"$2"\t"$4}1'

==

awk -v OFS="\t" '$4{sub("^","\n"$1"\t"$2"\t",$4)}1'

If you want formatted output you can use either OFS variable by -v OFS='\t' or pipe output via column -t

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.