0

A long short but is there a way to copy the end of select lines and append the text to that line. What I want to achieve is this.

what I have

>13_gnd
atcg
>14_galF
atgc

what I want

>13_gnd_gnd
atcg
>14_galF_galF
atgc    

So all lines starting with >copy the last word and append to the end of the line. Thanks.

4
$ sed 's/_[^_]*$/&&/' file         
>13_gnd_gnd
atcg
>14_galF_galF
atgc

The sed substitution will match the last underscore on each line and whatever is after it, to the end of the line. This is what the pattern _[^_]*$ does ("match an underscore possibly followed by other non-underscore characters, and the end of line"). It will replace this (including the underscore) with whatever was matched, twice (this is what && does in the replacement bit).

Since this appears to be a file in Fasta format, and since genomic sequences can't contain underscores, no special test is needed for > at the beginning of the line.

  • 1
    As the question refers to "all lines starting with >" and we don't don't whether the undercore can appear in other lines, too, the safe solution would be sed '/^>/s/_[^_]*$/&&/' file. However, I like the && replacement. (-: – Philippos Jun 22 '17 at 12:52
  • 1
    @Philippos There can't be underscores on other lines. The file is a Fasta file, and the non-header lines (the ones not starting with >) can't contain underscores. – Kusalananda Jun 22 '17 at 13:25
1

Short awk solution:

awk -F'_' '$0~/^>/{ $0=$0 FS $NF }1' file

The output:

>13_gnd_gnd
atcg
>14_galF_galF
atgc

Details:

  • -F'_' - field separator

  • $0~/^>/ - performs an action if the line starts with >

  • $0=$0 FS $NF - appends the last field value to the end

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.