0

I have fasta file (modelfasta.fasta) like this:

>seq1
AAAAAAAAAAAAAAA
GGGGGGGGGGG
>seq2
TTTTTTTTTTTTTTT
CCCCCCC

I am expecting output like this:

>header>seq1
AAAAAAAAAAAAAAAGGGGGGGGGGG
>header>seq2
TTTTTTTTTTTTTTTCCCCCCC

I tried with sed and awk command with fasta example file (modelfasta.fasta) but getting output in this way

awk '{printf $0""}' modelfasta.fasta 

>seq1AAAAAAAAAAAAAAAGGGGGGGGGGG>seq2TTTTTTTTTTTTTTTCCCCCCC

it removes newline just after header too and merges sequences with the header

the same result found with sed

sed ':a;N;$!ba;s/\n//g' modelfasta.fasta

>seq1AAAAAAAAAAAAAAAGGGGGGGGGGG>seq2TTTTTTTTTTTTTTTCCCCCCC

I want all the new lines removed except header's one, please help

  • Can you please format your code better. Not clear which is filename and which is content – Guru Jan 4 '17 at 9:46
  • the expected output has >header is that intentional ? – Sundeep Jan 4 '17 at 13:26
1

You would like to remove all newlines from lines that do not start with the fasta header character >.

awk '/^[>;]/ { if (seq) { print seq }; seq=""; print } /^[^>;]/ { seq = seq $0 } END { print seq }' data.fa

The Awk script is

/^[>;]/    { if (seq) { print seq }; seq=""; print }
/^[^>;]/ { seq = seq $0 }
END     { print seq }

... which will do three different thing depending on what it finds in the file.

  • A fasta header line (line starting with >), or a fasta comment line (line starting with ;): Print any sequence that we have remembered in seq if there is any (this belongs to the previous header). Clear the remembered sequence. Print the current line (the header, or the comment).
  • A fasta non-header (and non-comment) line: Concatenate the remembered sequence with the sequence on the line. This will effectively remove the newlines.
  • The end of the file: Print the sequence. This is the sequence associated with the last header in the file.

If you'd want to do some pretty-printing of the sequence, for example limit it to 60 characters per line:

#!/usr/bin/awk -f

function pretty(s) {
  p = "";
  n = 1;

  while (n < length(s)) {
    p = (p ? p "\n" : "") substr(s, n, 60);
    n += 60;
  }

  return p;
}

/^[>;]/  { if (seq) { print pretty(seq) }; seq=""; print }
/^[^>;]/ { seq = seq $0 } 
END      { print pretty(seq) }

Put that into prettyfasta.awk and make it executable (chmod +x prettyfasta.awk), then run it:

$ ./prettyfasta.awk data.fa
  • To also be able to have comments in the fasta file you may want tomodify the command a bit: awk '/^[>;]/ { if (seq) { print seq }; seq=""; print } /^[^>;]/ { seq = seq $0 } END { print seq }' – Jaleks Jan 4 '17 at 11:22
  • @Jaleks I've never ever seen that in use, but sure, the format allows it. I'll update my answer. – Kusalananda Jan 4 '17 at 11:25

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.