简体   繁体   中英

Replace String in XML file

I try to replace string in XML file with sed, but since its regular expression doesn't support non-greedy expressions, I encounter a problem.

XML Example:

<opt>
  <Node active="yes" file="/home/user/random_filename" last_time="17/07/14-00:02:07" time_in_min="5" />
</opt>

I want to find the file attribute, which is random string, and replace it with another string.

This command replaces the string, BUT removes the trailing data.

sed 's/file=".*"/file="new_file_name"/' file.xml

Output:

<opt>
   <Node active="yes" file="new_file_name" />
</opt>

How should I handle it?

Use "[^"]*" instead of ".*" :

<opt>
  <Node active="yes" file="/home/user/random_filename" last_time="17/07/14-00:02:07" time_in_min="5" />
</opt>

sed 's/file="[^"]*"/file="new_file_name"/'

<opt>
  <Node active="yes" file="new_file_name" last_time="17/07/14-00:02:07" time_in_min="5" />
</opt>

This doesn't use sed but when manipulating xml documents, you might want to consider xslt. It may be an over the top solution to your problem, but it's a great fit for working with xml.

filter.xsl:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" omit-xml-declaration="yes"/>

<!-- The replacement string is passed as a parameter.
     You can have as many param elements as you need. -->
<xsl:param name="NEW_NAME"/>

<!-- Copy all attributes and nodes... -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<!-- ...but when you encounter an element with a file attribute,
     replace it with the value passed in the parameter named $NEW_NAME. -->
<xsl:template match="@file">
    <xsl:attribute name="file">
        <xsl:value-of select="$NEW_NAME"/>
    </xsl:attribute>
</xsl:template>

</xsl:stylesheet>

A libxslt example (add as many --stringparam name/value pairs that you need):

xsltproc --stringparam NEW_NAME new_file_name filter.xsl file.xml

Result:

<opt>
    <Node active="yes" file="new_file_name" last_time="17/07/14-00:02:07" time_in_min="5"/>
</opt>
$ sed 's/\(.*file="\)[^"]*/\1new_file_name/' file
<opt>
  <Node active="yes" file="new_file_name" last_time="17/07/14-00:02:07" time_in_min="5" />
</opt>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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