在UNIX中使用SED命令替换整个字符串

时间:2015-09-03 13:08:26

标签: regex bash shell unix sed

我有以下XML

<properties></properties>

需要替换XML标头

SED

如 {{1}}使用命令{{1}}

帮助?

3 个答案:

答案 0 :(得分:0)

sed -i 's/refdataContent/properties/g' yourfile.xml怎么样?

答案 1 :(得分:0)

很难准确理解你想要做什么,我会尝试几种选择。

给出以下内容:

$ cat blah.xml
<?xml version='1.0' encoding='UTF-8'?>
<refdataContent xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.orbitz.com/refdataContent file:///opt/orbitz/schemas/content/refdataContent/1/0/refdataContent.xsd' xmlns='http://www.orbitz.com/refdataContent'>

  <entry key='com.orbitz.reference.api.hotel.HotelPlacementMetagyType.PREMIUMPLACEMENT'><![CDATA[Premium Placement]]></entry>
  <entry key='com.orbitz.reference.api.hotel.HotelAvailability.AVAILABLE'><![CDATA[Available]]></entry>
</refdataContent>

如果要删除的行中有唯一的字符串,请匹配该字符串并删除该行。让我们使用XMLSchema-instance

$ sed '/XMLSchema-instance/d' blah.xml
<?xml version='1.0' encoding='UTF-8'?>

  <entry key='com.orbitz.reference.api.hotel.HotelPlacementMetagyType.PREMIUMPLACEMENT'><![CDATA[Premium Placement]]></entry>
  <entry key='com.orbitz.reference.api.hotel.HotelAvailability.AVAILABLE'><![CDATA[Available]]></entry>
</refdataContent>

<properties></properties>替换该行:

$ sed 's/.*XMLSchema-instance.*/<properties><\/properties>/g' blah.xml
<?xml version='1.0' encoding='UTF-8'?>
<properties></properties>

  <entry key='com.orbitz.reference.api.hotel.HotelPlacementMetagyType.PREMIUMPLACEMENT'><![CDATA[Premium Placement]]></entry>
  <entry key='com.orbitz.reference.api.hotel.HotelAvailability.AVAILABLE'><![CDATA[Available]]></entry>
</refdataContent>

将行包裹在<properties></properties>

$ sed '/XMLSchema-instance/i\
> <properties>' blah.xml | sed '/XMLSchema-instance/a\
> </properties>'
<?xml version='1.0' encoding='UTF-8'?>
<properties><refdataContent xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.orbitz.com/refdataContent file:///opt/orbitz/schemas/content/refdataContent/1/0/refdataContent.xsd' xmlns='http://www.orbitz.com/refdataContent'>
</properties>
  <entry key='com.orbitz.reference.api.hotel.HotelPlacementMetagyType.PREMIUMPLACEMENT'><![CDATA[Premium Placement]]></entry>
  <entry key='com.orbitz.reference.api.hotel.HotelAvailability.AVAILABLE'><![CDATA[Available]]></entry>
</refdataContent>

答案 2 :(得分:0)

你的意思是改变

<refdataContent xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'xsi:schemaLocation='http://www.orbitz.com/refdataContent file:///opt/orbitz/schemas/content/refdataContent/1/0/refdataContent.xsd'xmlns='http://www.orbitz.com/refdataContent'>

<properties></refdataContent></properties>

可以使用s/refdataContent.*/properties>/完成。

如果你想删除那些<entry></entry>,请使用:

/<refdataContent/,/<\/refdataContent/{s/refdataContent.*/properties>/p;d}