You can do this simply enough in awk
:
$ awk -F'_' '{
split(FILENAME,n,/\./);
if(/^>/){
sample=$1;
sub(/>/,"",sample);
$$ awk -F'_' '{
split(FILENAME,n,/\./);
if(/^>/){
sample=$1;
sub(/>/,"",sample);
$0=">"n[1]
}
print > sample".fasta"
}' gene1.fasta gene2.fasta ... geneN.fasta
If I run this on the two files you gave, I get:
$ cat sample1.fasta
>gene1
GATCTCGTAGATGTGA
>gene2
ATGCTGTGAAGTA
$ cat sample2.fasta
>gene1
GATCTCGTAGATGTGA
>gene2
ATGCTGTGAAGTA
Explanation
-F'_'
: set the field separator to_
as an easy hack that lets us use$1
for the sample name (sample_NNN
, sosample
will be$1
andNNN
will be$2
).split(FILENAME,n,/\./);
:FILENAME
always holds the name of the file currently being processed. Here, we are splitting it on.
to get the gene's name. This assumes all of your files are named$geneName.fasta
. Thesplit
creates the arrayn
whose 1st element,n[1]
is the gene name.if(/^>/){
: if this is a fasta header line.sample=$1
: set the variablesample
to the sample's name. See the first note about-F'_'
.sub(/>/,"",sample);
: remove the>
from thesample
variable. We don't want that in the file name.$0=">"n[1]
: set the current line to be>
and the gene name.print > sample".fasta"
: print each (modified) line into the appropriate file name.