[英]Bash - quoted variable expansion mixed with sed yields bad substitution
I have problem with this sed oneliner 我有这个sed oneliner的问题
sed -i -n "1h; 1!H; ${g; :a s/\(Name=\"$key\".*<\!\[CDATA\[\"\)$val\(\"\]\]>\)/\1$deval\2/;ta p}"
Obviously I need to expand variable key
, val
and deval
in sed. 显然我需要在sed中扩展变量
key
, val
和deval
。 So I need the "
around sed command. 所以我需要
"
周围的sed命令。
With this command I get 有了这个命令,我得到了
bash: !H: event not found
escaping the !
逃避
!
corrects it 纠正它
sed -i -n "1h; 1\!H; ${g; :a s/\(Name=\"$key\".*<\!\[CDATA\[\"\)$val(\"\]\]>\)/\1$deval\2/;ta p}"
With this I get 有了这个,我得到了
bash: sed -i -n "1h; 1\\!H; ${g; :as/\\(Name=\\"$key\\".*<\\!\\[CDATA\\[\\"\\)$val\\(\\"\\]\\]>\\)/\\1$deval\\2/;ta p}" :bad substitution
So I guess the {
is a problem. 所以我想
{
是一个问题。 Trying to fix it like this 试图像这样修复它
sed -i -n "1h; 1\\!H; $\\{g; :as/\\(Name=\\"$key\\".*<\\!\\[CDATA\\[\\"\\)$val(\\"\\]\\]>\\)/\\1$deval\\2/;ta p}"
yields 产量
sed: -e expression 1, char 6: unknown command: "\\"
What is going on here? 这里发生了什么? How can I make this work?
我怎样才能做到这一点?
event not found
is only a problem in interactive shells because histexpand
is enabled by default. event not found
只是交互式shell中的问题,因为默认情况下启用了histexpand
。 If you either run set +H
first or put it in a script and run it from there, Bash will leave your !
如果您先运行
set +H
或将其放入脚本并从那里运行,Bash将离开您!
s alone. 独自一人
${..}
is variable substitution syntax (so a mangled value gives bad substitution
). ${..}
是变量替换语法(因此错位的值会导致bad substitution
)。 Let sed
treat it as a block of commands to do on the final line by escaping the $
, as in \\${ .. }
. 让
sed
通过转义$
来将其视为最后一行命令块,如\\${ .. }
。
In full: 在全:
set +H
key="foo"
val="bar"
deval="puppies"
echo 'Name="foo" <![CDATA["bar"]]>' > file
sed -i -n "1h; 1!H; \${g; :a s/\(Name=\"$key\".*<!\[CDATA\[\"\)$val\(\"\]\]>\)/\1$deval\2/;ta p}" file
cat file
Will print Name="foo" <![CDATA["puppies"]]>
将打印
Name="foo" <![CDATA["puppies"]]>
您可以使用单独的单引号字符串:
sed -i -n '1h; 1!H; ${g; :a s/\(Name='"$key"'.*<\!\[CDATA\[\"\)'"$val"'\(\"\]\]>\)/\1'"$deval"'\2/;ta p}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.