-1

I have bunch of sub-folders following the naming pattern x1, x2, x3, x4 ... and each containing the same script.sh file. What if I want to write a script, that changes certain line (say line 2) of that script file from x1 to whatever the folder's name is?

So for example, in folder x5, the 2nd line of script.sh should be x5, and in folder x39, the second line of script.sh should be x39.

Thanks!

Colin
  • 3
  • 1

1 Answers1

1

This one inserts the sub-folder name to the 2nd line of each script.sh

find . -name script.sh | while read f
do
    dir=$(basename $(dirname "$f"))
    sed -i "2 i $dir" "$f"
done

to replace the 2nd line, use c instead of i

find . -name script.sh | while read f
do
    dir=$(basename $(dirname "$f"))
    sed -i "2 c $dir" "$f"
done
Fabricator
  • 12,722
  • 2
  • 27
  • 40
  • A number of issues with this. Don't do `for f in $(find)` (see [this](http://stackoverflow.com/a/7039579/3076724) for better syntax. Also, you're not checking subfolder names (so this could change unintended files, and I'm not sure sure subfolder == recursive). Also, quote your variables, both in subshells and by themselves. – Reinstate Monica Please Jun 04 '14 at 18:57
  • @BroSlow, thanks! I've updated the answer per your suggestion. please edit if you see anything else problematic – Fabricator Jun 04 '14 at 19:17
  • it doesn't actually replace the 2nd line, but it inserts at the 2nd line. could you tell me how to replace? – Colin Jun 05 '14 at 23:10