Friday, May 3, 2024
26
rated 0 times [  26] [ 0]  / answers: 1 / hits: 63549  / 2 Years ago, tue, december 28, 2021, 8:20:48

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


More From » command-line

 Answers
6

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.


[#27361] Thursday, December 30, 2021, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pardsea

Total Points: 290
Total Questions: 115
Total Answers: 98

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
;