SED 命令不是从 bash 脚本运行的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20143035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:42:52  来源:igfitidea点击:

SED command not being run from bash script

bashshellscriptingsed

提问by user2294382

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.

我编写了一个 bash 脚本,它在文件上调用 sed 命令(除其他外)以完成 2 个不同字符串的查找/替换。

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!

运行脚本不会改变file.sql;但是,如果我运行打印到控制台的命令,例如 /usr/local/bin/sed -i -e 's/file_name1/file_name2/g;s//path_substring1//path_substring2//g' /path/to /file/file.sql 它完美运行!

回答by devnull

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.

使用不同的分隔符将避免/在模式中转义和替换的需要。