具有复杂模式和替换的 Sed 命令

具有复杂模式和替换的 Sed 命令

我将以下两个字符串保存为变量:

str1='ds-cfg-global-aci: (targetcontrol="2.16.840.1.113730.3.4.2 || 2.16.840.1.113730.3.4.17 || 2.16.840.1.113730.3.4.19 || 1.3.6.1.4.1.4203.1.10.2 || 1.3.6.1.4.1.42.2.27.8.5.1 || 2.16.840.1.113730.3.4.16 || 2.16.840.1.113894.1.8.31") (version 3.0; acl "Anonymous control access"; allow(read) userdn="ldap:///anyone";)'

str2='ds-cfg-global-aci: (targetcontrol="2.16.840.1.113730.3.4.2 || 2.16.840.1.113730.3.4.17 || 2.16.840.1.113730.3.4.19 || 1.3.6.1.4.1.4203.1.10.2 || 1.3.6.1.4.1.42.2.27.8.5.1 || 2.16.840.1.113730.3.4.16 || 2.16.840.1.113894.1.8.31 || 1.2.840.113556.1.4.319 ") (version 3.0; acl "Anonymous control access"; allow(read) userdn="ldap:///anyone";)'

我想使用 shell 脚本在脚本中将“str1”替换为“str2”。有人可以帮我吗?我正在尝试sed,但我做不到。

我尝试使用以下命令:

sed -i 's_ ( ds-cfg-global-aci: \(targetcontrol="2.16.840.1.113730.3.4.2 || 2.16.840.1.113730.3.4.17 || 2.16.840.1.113730.3.4.19 || 1.3.6.1.4.1.4203.1.10.2 || 1.3.6.1.4.1.42.2.27.8.5.1 || 2.16.840.1.113730.3.4.16 || )2.16.840.1.113894.1.8.31( "\) \(version 3.0 ; acl "Anonymous control access" ; allow\(read\) userdn="ldap:///anyone" ; \) ) _\12.16.840.1.113894.1.8.31 || 1.2.840.113556.1.4.319\2_' 2.xml

它不会抛出任何错误,但不会产生预期的输出。“2.xml”的文件内容只是模式。

答案1

我真的不明白你想用这个sed命令做什么。您似乎试图捕获某些组,但随后不使用它们。不管怎样,你想要的是这样的:

sed -i "s#$str1#$str2#" file

或者,如果您没有将字符串保存为变量:

sed -i 's#ds-cfg-global-aci: (targetcontrol="2.16.840.1.113730.3.4.2 || 2.16.840.1.113730.3.4.17 || 2.16.840.1.113730.3.4.19 || 1.3.6.1.4.1.4203.1.10.2 || 1.3.6.1.4.1.42.2.27.8.5.1 || 2.16.840.1.113730.3.4.16 || 2.16.840.1.113894.1.8.31") (version 3.0; acl "Anonymous control access"; allow(read) userdn="ldap:///anyone";)#ds-cfg-global-aci: (targetcontrol="2.16.840.1.113730.3.4.2 || 2.16.840.1.113730.3.4.17 || 2.16.840.1.113730.3.4.19 || 1.3.6.1.4.1.4203.1.10.2 || 1.3.6.1.4.1.42.2.27.8.5.1 || 2.16.840.1.113730.3.4.16 || 2.16.840.1.113894.1.8.31 || 1.2.840.113556.1.4.319 ") (version 3.0; acl "Anonymous control access"; allow(read) userdn="ldap:///anyone";)#' file

或者,由于唯一的区别似乎是 str1 不包含|| 1.2.840.113556.1.4.319,只需添加:

sed -i 's/")/ || 1.2.840.113556.1.4.319 ")/' file

相关内容