简体   繁体   English

bash:sed:变量中的正则表达式

[英]bash : sed : regex in variable

I'm getting totally crazy with the following script. 我对以下脚本感到非常疯狂。

The following command works as expected : 以下命令按预期工作:

echo a | sed 's/a/b/'

Output : 输出:

b

But this script doesn't : 但是这个脚本没有:

test="'s/a/b/'"
echo a | sed $test

Output : 输出:

sed: -e expression #1, char 1: unknown command : `''

I should really be stupid, but I don't see what I am missing. 我真的应该是傻瓜,但我不知道我错过了什么。

Thanks, 谢谢,

test="'s/a/b/'"
echo a | sed $test

is equivalent to: 相当于:

test="'s/a/b/'"
echo a | sed "'s/a/b/'"

Obviously sed doesn't understand the command with both " and ' , It interprets ' as a command. You can use either one of them: 显然sed并不理解带有"'的命令,它将'解释'为命令。你可以使用其中任何一个:

test='s/a/b/'

Or 要么

test='s/a/b/'

you may want this: 你可能想要这个:

kent$  test="s/a/b/"         

kent$  echo a | sed ${test}
b

or 要么

kent$  echo a | sed $test  
b

or 要么

test=s/a/b/

This is because your double wrapping your string. 这是因为你的双重缠绕你的字符串。 test="'s/a/b'" . test="'s/a/b'" Sed then gets 's/a/b/' as literal string. 然后,Sed将's/a/b/'作为文字字符串。 You only want sed to receive s/a/b/ . 你只想要sed接收s/a/b/
You only need to wrap the string in one set of quotes , otherwise the inner set of quotes will be interpreted as part of the argument. 您只需要将字符串包装在一组引号中 ,否则内部引号集将被解释为参数的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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