Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merge every last two lines in a 3-line row together

I wanted to merge every line 2-3 together and keep line 1. Here is the example of my text

>chrX:147147161-147148161
ATGATGGTGATGTACAGATGGGTTTTTGG
TTATCTAATTCATGTGTTGGTCAGATCAA
>chrY:16119725-16120725
CAGCTTTGTTCCGTTGCTGGTGAGGAACT
GACTCCCTGGGTGTAGGACCCTCCGAGCC

What I want it to look like

>chrX:147147161-147148161
ATGATGGTGATGTACAGATGGGTTTTTGGTTATCTAATTCATGTGTTGGTCAGATCAA
>chrY:16119725-16120725
CAGCTTTGTTCCGTTGCTGGTGAGGAACTGACTCCCTGGGTGTAGGACCCTCCGAGCC

I have tried several ways but none has been working so far. Here is what I have been trying to do

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

> sed '/>$/,/>$/ {//b; N; s/\n//;}' file.txt

This command could not merge my lines. I also tried this before

> paste -d "" - - < txt.file . 

This only merge my chr line and the sequence line, which was not what I wanted. Can someone give my some suggestions? Thank you!

>Solution :

Assumptions:

  • sequence lines do not contain (trailing) white space
  • sequence lines do not end with a \r (windows/dos line ending)
  • a sequence spans exactly 2 lines (not 1 line, not 3+ lines)
  • NOTE: additional logic can be added to address any invalid assumptions

A couple variations on an awk idea:

awk '
(NR%3)==2 { line2=$0; next }
(NR%3)==0 { print line2 $0; next }
1
' file.txt

####################

awk '
(NR%3)==2 { line2=$0; next }
          { print line2 $0 }
(NR%3)==0 { line2="" }
' file.txt

Both of these generate:

>chrX:147147161-147148161
ATGATGGTGATGTACAGATGGGTTTTTGGTTATCTAATTCATGTGTTGGTCAGATCAA
>chrY:16119725-16120725
CAGCTTTGTTCCGTTGCTGGTGAGGAACTGACTCCCTGGGTGTAGGACCCTCCGAGCC
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading