This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Replace FASTA file headers

Hello everyone,

I try to replace the headers A of a FASTA file (file.fasta) with headers B.

For this, I have a list which match the headers names.

>A_1     >B_1
>A_2     >B_2
>A_3     >B_3
etc...

I am using this loop to replace the headers:

cat list | while read f ;
do
 echo $f > temp_file
 A=$(awk '{print $1}' temp_file ) ;
 B=$(awk '{print $2}' temp_file  ) ;
 sed -i  's/$A/$B/g' file.fasta ;
done

But this simple loop does not work. Would anyone know if I have made an obvious mistake?

fasta fasta sed loop

My apologizes, I thought the thumb up was the way to validate the answer.

If an answer was helpful, you should upvote it; if the answer resolved your question, you should mark it as accepted. You can accept more than one if they work.
Upvote|Bookmark|Accept

The name in your B fie is a prefix or a different name? Because if it is a prefix you can replace it directly in the A file. And btw, to use bash variables inside of sed you need to use double-quotes.

Use dedicated tools such as seqtk and seqkit to replace fasta headers from a file.

1 answer

You can turn your substitutions file into a list of sed commands and run that on the file. Assuming your subs file is separated by spaces:

Run: sed -i -e 's|^|s\/|g' -e 's| \+|\/|g' -e 's|$|\/g|g' subs.txt on the file containing the substitutions, which gives:

s/>A_1/>B_1/g
s/>A_2/>B_2/g
s/>A_3/>B_3/g

Then,

sed -i -f subs.txt myfile.fasta should give you the edited file.

Log in to answer this question.