I have fasta files, coming from different samples eg: 01.fasta, 02.fasta, etc.

All of them contain OTU list with the following pattern:



I would like to add the file's name (eg. 01, 02, etc) to each >OTU* line in the fasta file to receive the following: >OTU1_01, >OTU2_01, etc.

Can you help me write a script that automatically does it for all files in my folder?


Make sure you have a backup of your files before starting to change them all

You can run something like the following:

for i in *.fasta; do nr="${i%.fasta}"; sed -i 's/^>OTU\(.*\)$/>OTU\1_'$nr'/' "$i"; done

if you have a version of sed that supports -i (in place editing).

The nr="${i%.fasta}" part gets you the number from the filename. The \(.*\) matches the number after >OTU, which then gets reinserted with \1


gawk 4.1.0 onwards, an in-place editing option is available. So in one fell swoop

awk -i inplace -v INPLACE_SUFFIX=.bak '
  BEGINFILE{x=FILENAME; sub(/\..*/, "", x)};
  /^>OT/{$0 =$0"_"x};
  {print}' *.fasta

will update files as needed in-place. -v INPLACE_SUFFIX=.bak causes original files to be backed up with a .bak suffix

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.