简体   繁体   English

将bash脚本变量插入正则表达式字符串

[英]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您的命令有一些问题

  • You need double quotes for the variable to expand您需要双引号来扩展变量
  • As a result of the double quotes, you would need to escape the double quotes within the command由于双引号,您需要在命令中转义双引号
  • The variable contains the forward slash / 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个问题:

  1. You are using single-quotes which means the Bash substitutions do not get expanded within the string -- you need to use double-quotes and escape your in-string double-quotes.您使用的是单引号,这意味着 Bash 替换不会在字符串中得到扩展——您需要使用双引号并转义您的字符串内双引号。
  2. When your path gets expanded, the character (ie / ) you're using to delimit the substitution expressions collides with it.当您的路径被扩展时,您用来分隔替换表达式的字符(即/ )会与它发生冲突。
  3. Your 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM