使用自定义字符串的sed替换在替换命令'/'中获取错误标志

时间:2016-09-27 22:02:59

标签: bash sed escaping special-characters double-quotes

我正在使用macOS Sierra,而且我正在尝试从配置文件中操纵一个键的值。

为了实现我正在使用(对于简单值可以正常工作):

sed -i .bak "/^$KEY/s/\(.[^=]*\)\([ \t]*=[ \t]*\)\(.[^=]*\)/\1\2$VALUE/" $CONFIG_FILE

不幸的是,我的字符串$ VALUE与许多特殊字符相当复杂,给我错误:

  

替换命令中的错误标志:'/'

我的$ VALUE被声明为:

VALUE='<Request xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" ReturnPolicyIdList="false" CombinedDecision="false"> <Attributes Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource"> <Attribute IncludeInResult="false" AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id"> <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">test </AttributeValue> </Attribute> </Attributes> <Attributes Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action"> <Attribute IncludeInResult="false" AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id"> <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">testing something</AttributeValue> </Attribute> </Attributes> </Request>'

由于我将双引号作为$ VALUE值的一部分,因此在声明时我不能使用双引号而不是单引号...有什么想法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

问题是$VALUE包含应该转义的斜杠,因为它与substiture命令的分隔符冲突

这不方便,因为如果它改变了,你必须再次逃脱它们。不过,这是一个解决方案。

另一个更简单的解决方案是为s命令使用替代的分隔字符,该字符不在$VALUE字符串中,例如%%的机会较少一个字符串,否则也可以使用|

sed -i .bak "/^$KEY/s%\(.[^=]*\)\([ \t]*=[ \t]*\)\(.[^=]*\)%\1\2$VALUE%" $CONFIG_FILE

或管道:

sed -i .bak "/^$KEY/s|\(.[^=]*\)\([ \t]*=[ \t]*\)\(.[^=]*\)|\1\2$VALUE|" $CONFIG_FILE
相关问题