Shell – Sed to copy part of file name into another contents of file with same substring

filessedshell-script

For every file with the specified extension within one directory, I would like to use just a substring from the filename to add to another file and output as a file with a different extension but the same substring.

I have found some similar examples to what I would like to do but I am writing a bash script so I have run into some challenges I have had a hard time finding examples of.

For example, I would start with filename.sample and I only want the substring "filename".

What I tried to do is:

for i in /path/to/*.sample
do
   bar="${i%%.sample*}"
   sed "s/^>\(.*\)/>\1;label=${bar##*/};/" "$i" > "$i"_bar  \;
done

The contents of *.sample files are as follows:

*.sample

> MEWFJWRNFF_141
AB28974UJBDASX

The desired output is:

Output_bar
> MEWFJWRNFF_141; label=filename;
AB28974UJBDASX

Let me know if I have been unclear in any way! Thank you!

Best Answer

for i in /path/to/*.sample
do
    str="; label=$(basename -s.sample $i);"
    sed "/^>/ s/$/$str/" "$i"
done
  • basename command gives only the name of file, stripping away path. And -s.sample will strip the extension
  • So, if i is /path/to/filename.sample , str will contain ; label=filename;
  • /^>/ s/$/$str/ will find a line starting with > and add the contents of str variable to end of that line

I do not get how you want the output file to be named. If i is /path/to/filename.sample, "$i"_bar will give /path/to/filename.sample_bar

Related Question