This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Rename .fasta headers and save parsed files in new folder [bash]

Hi!

I have folder with multiple fasta files, each file has few sequences like this:

>KLTH0E08624g KLTH0E08624g
MAREITDIKEFLELARRADVKTATVKINKKLNKSGKAFRQTKFKVRGSRYLYTLIVNDAG

I need to make a bash script which parse that files to get new headers in each fasta (first 4 letters):

>KLTH
MAREITDIKEFLELARRADVKTATVKINKKLNKSGKAFRQTKFKVRGSRYLYTLIVNDAG

and save these files in another folder. I am new in bash and and I can not handle it by myself. For now I have:

for f in $(ls path_to_folder/GL3*.fasta)
do
    # here bash command to correct that headers and save in:
    "/corrected/$f"
done

Kindly help

fasta bash

This is probably the most asked question on the forum - have you looked at other threads for ideas?

I do not know how to extract exactly first 4 letters. I have checked other posts but in is not clear for me.

2 answers

You can use cut command with -c. https://colab.research.google.com/drive/1O3KUjo7qwV5bLUjy5eAqfgUu3wriJQLE#scrollTo=l7KgHme0vjeY

printf ">KLTH0E08624g KLTH0E08624g\nMAREITDIKEFLELARRADVKTATVKINKKLNKSGKAFRQTKFKVRGSRYLYTLIVNDAG\n" > example.fasta
while IFS='' read -r line; do
  case $line in
    ">"*) echo "$(echo $line | cut -c -5)";;
    *) echo "$line";;
  esac
done < example.fasta

Results in:

>KLTH
MAREITDIKEFLELARRADVKTATVKINKKLNKSGKAFRQTKFKVRGSRYLYTLIVNDAG

With awk

awk '{if(/^>/){print substr($0,1,5)}else{print $0}}' input.fasta > output.fasta

Log in to answer this question.