Append file name to fasta file headers in Linux

How do we append the file name to fasta file headers in multiple fasta-files in Linux?

Using awk:

awk 'NR==1{$0=$0"|"FILENAME}1' file.fasta

Gave awk a try, but this appears to print the filename in the first header only, not to change it in place, and also this does not affect the subsequent headers. Any alternative solutions?

Post sample input and expected output in code tags

I did, but it was removed.. here goes again: fasta files (e.g. sample_1.fasta) in format:

>node_1
atgatgatgat
>node_3
gtcgtcgtcgtcgtc
>node_12
gtagtagta

Expected output:

>sample_1_node_1
atgatgatgat
>sample_1_node_3
gtcgtcgtcgtcgtc
>sample_1_node_12
gtagtagta
awk '/>/{sub(">","&"FILENAME"_");sub(/\.fasta/,x)}1' sample_1.fasta

Brilliant, thank you! :b:

Is it also possible to modify this code, for example using a for-loop, to perform this action on all .fasta files in a directory (outputing the modified files to a new directory or similarly)?

for file in /source_dir/*.fasta
do
        fname="${file##*/}"
        awk '/>/{sub(">","&"FILENAME"_");sub(/\.fasta/,x)}1' "$file" > /dest_dir/$fname"
done
for file in /source_dir/*.fasta
do
        fname="${file##*/}"
        awk '/>/{sub(">","&"FILENAME"_");sub(/\.fasta/,x)}1' "$file" > /dest_dir/$fname"
done

OR this

$ awk '/>/{sub(/\..*/,x,FILENAME);$0=FILENAME"_"$2}1' FS=">" sample_1.fasta 

sample_1_node_1
atgatgatgat
sample_1_node_3
gtcgtcgtcgtcgtc
sample_1_node_12
gtagtagta