简体   繁体   English

Sed 命令:在目标字符串前后使用通配符搜索模式

[英]Sed Command: Searching pattern with wildcard before and after the target string

Content of sample.xml is like the one below. sample.xml 的内容如下所示。

<Name="com.name1.sample.date" level="ERROR"/>
<Name="com.name2.test" level="WARNING">
<Name="com.name3.type.yeah.trace" additivity="false" level="DEBUG">

I am trying to use sed and just replace the value of the "level paramater" on all lines.我正在尝试使用 sed 并在所有行上替换“级别参数”的值。 However, using (*) as wildcard is not working for pattern matching.但是,使用 (*) 作为通配符不适用于模式匹配。

I'd like the output to be like the one below.我希望 output 与下面的一样。

<Name="com.name1.sample.date" level="INFO"/>
<Name="com.name2.test" level="WARN">
<Name="com.name3.type.yeah.trace" additivity="false" level="UPDATE">

Basically: From this pattern *level="<pattern>"* To this pattern *level="<updated>"*基本上:从这个模式*level="<pattern>"*到这个模式*level="<updated>"*

Where the * could be any pattern. * 可以是任何模式。

I did some research here and was able to make it work for wildcard at the beginning but not at the end so I am doing a special handling for each pattern that has a different ending.我在这里做了一些研究,并且能够使其在开始时适用于通配符,但在结束时不起作用,所以我对每个具有不同结尾的模式进行了特殊处理。 Below is my code.下面是我的代码。

sed 's|="'"$logger_type"'".*|="'"$logger_type"'" level="'"$update_check"'"/>|g'

Where $logger_type is the name being referenced, and its level should be updated to whatever the content of $update_check其中 $logger_type 是被引用的名称,其级别应更新为 $update_check 的任何内容

Basically: From this pattern *level="<pattern>"* To this pattern *level="<updated>"*基本上:从这个模式*level="<pattern>"*到这个模式*level="<updated>"*

Since your input is line-oriented, we can use " logger_type " as an address regexp to process only the lines matching the regular expression;由于您的输入是面向行的,我们可以使用" logger_type "作为地址正则表达式来仅处理与正则表达式匹配的行; therewith we can simplify the substitution pattern to only specify level="…" and leave other attributes (like additivity ) as they are.因此,我们可以简化替换模式以仅指定level="…"并保留其他属性(如additivity )。

sed /\"$logger_type'"/s/level="\w*"/level="'$update_check\"/ sample.xml

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

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