如何使用sed替换字符串中间的匹配字符

时间:2016-01-11 08:25:06

标签: regex linux bash sed

我有一个XML文件“datasources.xml”

<item-map group="org.base" datasource="localderby"/>
<item-map group="org.base.pos" datasource="localderbypos"/>
<item-map group="org.base.hr" datasource="localderbyhr"/>

并需要类似于此

的输出
<item-map group="org.base" datasource="localpostgres"/>
<item-map group="org.base.pos" datasource="localpostpos"/>
<item-map group="org.base.hr" datasource="localposthr"/>

所以我通过命令

生成了输出
  

sed -e's / datasource =“localderby”/ datasource =“localpostgres”/ g'-e's / datasource =“localderby([az])*”/ datasource =“localpost * / g'datasources。 XML

通过第一个表达式,我得到了我想要的“localpostgres”,但第二个表达式丢失了。有人可以提供帮助吗,请给我建议?谢谢转发。

1 个答案:

答案 0 :(得分:2)

使用扩展的正则表达式(sed -r)和+代替*,并进行分组:

sed -r -e 's/datasource="localderby"/datasource="localpostgres"/g' -e 's/datasource="localderby([a-z]+)"/datasource="localpost\1"/g' datasources.xml