0

I have file1.fa in the format as below:

>XXX[YY]
ZZZZZZ>XXX[YY]
ZZZZZZ>XXX[YY]
ZZZZZZ

I was trying to add a new lines before the forward arrow using sed command but it doesn't work.

sed 's/ \?\>/ \n\>/g' file1.fa > file2.fa

The desired file format:

>XXX[YY]
ZZZZZZ
>XXX[YY]
ZZZZZZ
>XXX[YY]
ZZZZZZ

I have tried it with other characters and the script working just fine.

I wonder if there happened to be any restriction that I have to include when dealing with the forward arrow in sed? Or anybody know what is going wrong here?

4

You should not escape > (\> is a special word-boundary pattern).

This is working for me (using GNU sed):

 sed -e 's/>/\n>/g' file1

For your case the output which I am getting is:


>XXX[YY]
ZZZZZZ
>XXX[YY]
ZZZZZZ
>XXX[YY]
ZZZZZZ
  • I made some error in typing my script earlier (already updated). Btw your script is working here as well, thanks! – web Apr 9 at 7:10
  • @Kusalananda thanks for clarifying about \> ! – web Apr 9 at 7:12
1

The \> is a special pattern that will match the zero-width space between a word and non-word character. The > is not special in any sense, so it does not need to be escaped.

To add a newline before each > on each line except the first, using standard sed, you may do

$ sed '2,${ y/>/\n/;s/\n/&>/g; }' file
>XXX[YY]
ZZZZZZ
>XXX[YY]
ZZZZZZ
>XXX[YY]
ZZZZZZ

Standard sed can't insert a newline with s/>/\n>/g, so we have to do it in two steps.

The 2,$ addresses all lines in the input except for the initial line. The commands within { ... } will be applied to these lines.

The y/>/\n/ command is replacing all instances of the character > with a newline. The y command can insert newlines in standard sed.

The s/\n/&>/g replaces each generated newline with the matched newline followed by >. When & occurs in the replacement part of a s command, it inserts whatever the pattern matched.

1

I tried with below method and it worked fine

command: sed "/^[^>]/s/>.*/\n&/g" filename

output

sed "/^[^>]/s/>.*/\n&/g" filename
>XXX[YY]
ZZZZZZ
>XXX[YY]
ZZZZZZ
>XXX[YY]
ZZZZZZ

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.