4

I wrote my script using the the directory ~/deleted (it's a long script). after using ~/deleted for the whole script. I want to let the user choose the directory by putting the path in ~/.rm.cfg.

My file starts like this:

#!/bin/bash

defaultpath=~/deleted

if [ -s ~/.rm.cfg ]
then
    defaultpath=$(head -1 ~/.rm.cfg)
fi

I need to replace every ~/deleted with $defaultpath in my script. Is there a way to do it in command line such that it saves and replaces the original file?

I can't get either perl or sed to work.

  • The first line defaultpath=~/deleted will be added again after all "~/deleted" strings have been replace by $defaultpath – lonewarrior556 Aug 6 '14 at 17:51
  • Is there a reason why you don't create a new file and then rename that to replace the old file? – celtschk Aug 6 '14 at 18:04
  • 1
    sed should suffice. What did you try? – Bernhard Aug 6 '14 at 18:10
8
sed -i 's|~/deleted|"$defaultpath"|g' file.sh

Explanation:

  • -i tells sed to modify the file in place.

  • s|~/deleted|"$defaultpath"|g tells sed to replace ~/deleted with "$defaultpath" whereever it finds it.

Extra feature: preserve ~/deleted on the third line

You did not ask for this but, in your example script, it would be nice to leave ~/deleted unchanged on the third line where it is used to define defaultpath. To change all instances of ~/deleted except the one on the third line, use:

sed -i -e '3n' -e 's|~/deleted|"$defaultpath"|g' file.sh

This adds the single sed command 3n which tells sed to skip the third line.

  • I wasn't including the quotes around $defaultpath thank you – lonewarrior556 Aug 6 '14 at 18:58
  • hahha, now you're just showing off – lonewarrior556 Aug 6 '14 at 20:07

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.