sed to replace pattern with filename

Hi all,

I'm trying to replace a pattern/string in about 100 files with the filename using following commands but getting nowhere:

for f in .fa; do sed "s/^>./>$f/g" $f > $f_v1.fa; done

for f in .fa; do sed 's/^>./>`echo $f`/' > $fa_v1.fa; done

Basically I want to change any line that starts with > to >filename.

Thanks for any suggestion.

 
for f in *.fa; do sed 's/^>.*/>'$f'/' $f > ${f}_v1.fa; done

This solves my problem. Thank you.

By the way can you explain the single quotation '$f'? I have tried with double quotation and it simply replaced the line with "$f". And why the curvy bracket at the end? Apology if the answers are very obvious. I'm actually a biologist. Thank you.

To single quotes gets the shell variable $f as part of the sed script between the first and last quote.

Curvy bracket is used to distinguish the actual variable name. Without curvy bracket is will consider the whole as variable name: $f_v1.fa; but with curvy bracket it will consider only $f as variable name: ${f}_v1.fa;

To be precise, without the braces, the variable name ends with the character before the dot, ${f_v1}.fa , since the dot is not allowed in a variable name [1].

Regards,
Alister

  1. ksh does allow dots in a variable name, but those names MUST appear within braces
1 Like