Concatenate multiple fasta files into one file per unique entry I have eight fasta files, one per gene, with 106 fasta entries per file, like this:

gene1.fasta:

&gt;sample1_434564
GATCTCGTAGATGTGA
&gt;sample2_2346764
GATCTCGTAGATGTGA


gene2.fasta:

&gt;sample1_532345
ATGCTGTGAAGTA
&gt;sample2_6040103
ATGCTGTGAAGTA


What I want to do is create one fasta file per sample so that I get all gene sequences for that sample in one file. As you can see, the sample ID is the same before the _ in the fasta headers, but the rest is unique for each fasta file. 

Is  there any way to do this with awk or other command-line tools? 

Desired output:

Sample1.fasta

&gt;gene1
GATCTCGTAGATGTGA
&gt;gene2
ATGCTGTGAAGTA


Sample2.fasta

&gt;gene1
GATCTCGTAGATGTGA
&gt;gene2
ATGCTGTGAAGTA
You can do this simply enough in awk:

$ awk -F'_' '{
               split(FILENAME,n,/\./); 
               if(/^&gt;/){
                  sample=$1; 
                  sub(/&gt;/,"",sample); 
                  $0="&gt;"n[1]
               }
               print &gt; sample".fasta"
             }' gene1.fasta gene2.fasta ... geneN.fasta


If I run this on the two files you gave, I get:

$ cat sample1.fasta 
&gt;gene1
GATCTCGTAGATGTGA
&gt;gene2
ATGCTGTGAAGTA

$ cat sample2.fasta 
&gt;gene1
GATCTCGTAGATGTGA
&gt;gene2
ATGCTGTGAAGTA


Explanation


-F'_' : set the field separator to _ as an easy hack that lets us use $1 for the sample name (sample_NNN, so sample will be $1 and NNN 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. The split creates the array n whose 1st element, n[1] is the gene name.
if(/^&gt;/){ : if this is a fasta header line.
sample=$1 : set the variable sample to the sample's name. See the first note about -F'_'.
sub(/&gt;/,"",sample); : remove the &gt; from the sample variable. We don't want that in the file name.
$0="&gt;"n[1] : set the current line to be &gt; and the gene name.
print &gt; sample".fasta" : print each (modified) line into the appropriate file name.