bash 脚本中的 sed 不起作用:但它适用于命令行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8827097/
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 01:17:03  来源:igfitidea点击:

Sed inside bash script not working: But it works on command line

bashscriptingsed

提问by Matthew Hoggan

I have tried the following on the command line and they work, but when I place them in a bash script I get an error (see below):

我在命令行上尝试了以下操作并且它们可以工作,但是当我将它们放在 bash 脚本中时出现错误(见下文):

sed -e "s/INSERT_ME_HERE/"${ROOT_BUILD_HOME}"/g" ./Doxyfile > ./tmp && mv ./tmp ./Doxyfile
sed -e "s/INSERT_ME_HERE/'${ROOT_BUILD_HOME}'/g" ./Doxyfile > ./tmp && mv ./tmp ./Doxyfile
sed -e "s/INSERT_ME_HERE/`echo ${ROOT_BUILD_HOME}`/g" ./Doxyfile > ./tmp && mv ./tmp ./Doxyfile

The error I am getting is:

我得到的错误是:

sed: -e expression #1, char 19: unknown option to `s'

However like I said I am using it from the command line and it works:

但是就像我说的那样,我是从命令行使用它的,它可以工作:

[mehoggan@hogganz400 Doxygen]$ ROOT_BUILD_HOME=MONKEY; sed -e "s/INSERT_ME_HERE/`echo ${ROOT_BUILD_HOME}`/g" ./Doxyfile | grep MONKEY
INPUT                  = MONKEY

Why does it work under one case and not the other?

为什么它在一种情况下有效,而在另一种情况下无效?

Also ROOT_BUILD_HOMEis set, I echo it right before the sed expression within the shell script.

ROOT_BUILD_HOME已设置,我在 shell 脚本中的 sed 表达式之前回显了它。

echo `date`: "Going to run doxygen on source and move to ${ROOT_BUILD_HOME}";

回答by ruakh

I'm guessing that ROOT_BUILD_HOMEstarts with a /, which sedis interpreting as ending your replacement-string. Am I right? If so, then try using a different separator:

我猜它ROOT_BUILD_HOME以 a 开头/,它sed被解释为你的替换字符串的结尾。我对吗?如果是这样,请尝试使用不同的分隔符:

sed -e "s#INSERT_ME_HERE#${ROOT_BUILD_HOME}#g" ./Doxyfile > ./tmp && mv ./tmp ./Doxyfile

回答by Sergey Benner

#!/bin/bash

ABC=`echo ${ROOT_BUILD_HOME}`
echo $ABC
sed -e 's/INSERT_ME_HERE/'$ABC'/g' <./Doxyfile > ./tmp && mv ./tmp ./Doxyfile

hope this helps

希望这可以帮助