SED command not being run from bash script

2019-01-12 05:27发布

问题:

I have written a bash script which calls a sed command (amongst other things) on a file to complete a find/replace of 2 different strings.

The trouble is, after running the script, I check the files and nothing has been updated. However, if I run the commands that are being produced (I echo them as output anyway) then they work.

For example, inside the script I have:

echo "/usr/local/bin/sed -i -e 's/${String1}/${String1R}/g;s/\/${String2}\//\/${String2R}\//g' ${ROOT_DIR}/data/file.sql"
/usr/local/bin/sed -i -e 's/${String1}/${String1R}/g;s/\/${String2}\//\/${TString2R}\//g' ${ROOT_DIR}/data/file.sql

Running the script does not change file.sql; however, if I run the command that is printed to console e.g. /usr/local/bin/sed -i -e 's/file_name1/file_name2/g;s//path_substring1///path_substring2//g' /path/to/file/file.sql it works perfectly!

回答1:

Use double quotes instead of single quotes. Single quotes would prevent variable expansion.

/usr/local/bin/sed -i -e "s/${String1}/${String1R}/g;s/\/${String2}\//\/${TString2R}\//g" ${ROOT_DIR}/data/file.sql

Moreover, it seems that your variables are path strings which might contain forward slashes, i.e. /. In that event use a different separator:

"s|${String1}|${String1R}|g"

Using a different separator would obviate the need of escaping / in the pattern and replacement.