Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I am trying to write the following bash script:

HOME_DIR=/opt/my_home
find ./CONFIG -type f -exec sed -i "s/_HOME_DIR_/$_HOME_DIR/g" {} \;

The line that I want to be changed in the files is this:

users                   = "_HOME_DIR_/config/data/_DOMAIN_/users.conf"

So the end result must be:

users                   = "/opt/my_home/config/data/_DOMAIN_/users.conf"

But I am not getting that... I guess it's because of escape chars...

Can anyone shed some light?

Thanks

share|improve this question
    
you mean, s(h)ed some light –  Alexandre Holden Daly Oct 31 at 0:15

2 Answers 2

up vote 3 down vote accepted

In circumstances where the replacement string or pattern string contain slashes, you can make use of the fact that GNU sed allows an alternative delimiter for the substitute command. Common choices for the delimiter are the pipe character | or the hash # - the best choice of delimiting character will often depend on the type of file being processed. In your case you can try

sed -i "s#_HOME_DIR_#$HOME_DIR#"

Also note that you mistyped your variable name $HOME_DIR (it does not start with an underscore).

$ HOME_DIR=/opt/my_home
$ echo "_HOME_DIR_/config/data/_DOMAIN_/users.conf" | sed "s#_HOME_DIR_#$HOME_DIR#"
/opt/my_home/config/data/_DOMAIN_/users.conf

Just fyi you may want to avoid using all-caps for user variables in your script - they should be reserved for system variables. Also the g switch is not necessary unless you want to make multiple replacements on a single line.

share|improve this answer
    
Thanks, it works! :) –  Felipe Caldas Jan 22 at 3:24

Hardcoding the variable 'opt/home' will work like this ..

find ./CONFIG -type f -exec sed -i "s/\_HOME\_DIR\_/opt\/home/g" {} \;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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