[英]Inserting bash script variable into regex string
I'm trying to run a sed command in a bash script I have which replaces a string between two quotation marks from another file with another string.我正在尝试在我拥有的 bash 脚本中运行 sed 命令,该脚本将另一个文件中两个引号之间的字符串替换为另一个字符串。
The file I'm editing:我正在编辑的文件:
path="text"
Bash script: bash 脚本:
userPath=$(pwd)
sed -i 's/path=".*"/path="${userPath}"/g' file
but after running the script, my file gets edited as this instead of the actual path that gets outputted from the pwd (etc. path="/home/Downloads") command:但是在运行脚本之后,我的文件被编辑为这个,而不是从 pwd (etc. path="/home/Downloads") 命令输出的实际路径:
path="${userPath}"
I tried replacing the single quotes on the outside to double quotes, but I got some "unknown option to 's'" error when running the script.我尝试将外部的单引号替换为双引号,但在运行脚本时出现“'s' 的未知选项”错误。 Attempting to add extra quotes and escape them like below did not work either.尝试添加额外的引号并像下面这样转义它们也不起作用。
sed -i 's/path=".*"/path="\"${userPath}\""/g' file
There are a few issues with your command您的命令有一些问题
/
character which will conflict with sed
s default delimiter.该变量包含与sed
默认分隔符冲突的正斜杠/
字符。For your code to work, you would need to change it to;为了使您的代码正常工作,您需要将其更改为;
$ sed -Ei.bak "s~path=\".*\"~path=\"${userPath}\"~g" file
-i.bak
will create a backup of the file -i.bak
将创建文件的备份
You have 3 problems:你有3个问题:
/
) you're using to delimit the substitution expressions collides with it.当您的路径被扩展时,您用来分隔替换表达式的字符(即/
)会与它发生冲突。sed
command seems to not work on my Mac OS X and this may be because it differs between gsed
and the Mac version.您的sed
命令似乎不适用于我的 Mac OS X,这可能是因为它在gsed
和 Mac 版本之间有所不同。 Here's the corrected expression using #
as the delimiting character:这是使用#
作为分隔符的更正表达式:
sed -i -e "s#path=\".*\"#path=\"${userPath}\"#g" hello.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.