4

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!

  • 1
    The unnecessary \; at the end of the sed command makes it choke looking for a file called ; I think – steeldriver Aug 21 '16 at 11:09
  • though that shouldn't stop sed from processing the first file. – ilkkachu Aug 21 '16 at 14:10
4
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

  • 1
    Thank you, this is exactly what I needed! You are correct, what I wrote here for the output is not exactly ideal so I set the output file to "${i%%.sample*}"_bar and the output is perfect. :) – Alina Orozco Aug 21 '16 at 18:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.