Hi,

I have 10 fasta files (each file with 20 gene sequences from each of the 10 samples). I would like to create 20 files, specific to each gene from 10 samples. 
I proceeded as follows to extract genes with the file_name in header:

    pyfasta extract --header --fasta test.fasta gene_name1 | awk '/^>/ {$0=$0 "_sample1"}1' > gene_name1.fasta
        
Output:

    >gene_name1_sample1
    ATGC
       
I am successful in creating multiple gene fasta files for each gene from each sample (a part from loop):
 

     pyfasta extract --header --fasta $sample.fasta gene_name1 >> gene_name1.fasta 
     pyfasta extract --header --fasta $sample.fasta gene_name2 >> gene_name2.fasta 

But, I am unable to add file_name to the header of files in loop (but can do for 1 file as mentioned in the beginning).

Kindly guide.

Thanks.
The question is pretty generalized with the use of terms. From what I understand, this should work:

If each sample file are not single line fasta, [linearize][1], on commandline:

    for file in *.fasta; do awk '/^>/ {printf("\n%s\n",$0);next; } { printf("%s",$0);}  END {printf("\n");}' < $file > "`basename $file .fasta`_single-line.fasta"; done

Then run this python script:

    #!/usr/bin/env python
    
    import glob
    from collections import defaultdict
    
    genes = defaultdict(list)
    
    for file in glob.glob('*_single-line.fasta'):
    	with open(file, 'r') as f:
    		for line in f:
    			if line.startswith(">"):
    				# Gene ID : (sample name, sequence)
    				genes[line.strip().split('>')[1]].append((file.split('.fasta')[0], next(f).strip()))
    
    for g in genes:
    	# open fasta per gene name
    	with open(g + '.fasta', 'w') as out:
    		# for each sample name and sequence
    		for n in range(len(genes[g])):
    			# print to file, >gene_sample, sequence
    			out.write('>' + g + '_' + genes[g][n][0] + '\n' + genes[g][n][1])



  [1]: https://www.biostars.org/p/9262/