1

I have a XML tag for example

<tag name="abc"></tag>

I wanted to replace the string inside "" with the tag name i.e the upper XML tag should be become now

<abc name="abc"></abc>
  • 1
    What XML parser are you using? – Anthon Jul 14 '14 at 10:08
1

You shouldn't use something like sed/awk for it and use an xml/xslt processor, such as xmlstarlet instead.

Create an xslt file with a template such as and save it under transform.xsl:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="tag">
    <xsl:element name="{@name}">
      <xsl:attribute name="name">
        <xsl:value-of select="@name"/>
      </xsl:attribute>
    </xsl:element>
  </xsl:template>
</xsl:stylesheet>

You can then apply the transformation on your xml document via xmlstarlet tr transform.xsl input.xml

-1

Do it as you prefer but here it is:

STR='<tag name="abc"></tag>'
AUX=$(echo $STR | cut -d"\"" -f2)
echo $STR | sed "s/tag/$AUX/g"
  • What about tags like <tag class="foo" name="abc">? Or any of the many cases where there may be a " before the field you care about? Or tags that span multiple lines with the name on a different one? How would this be run on an XML file (which is presumably what the OP has)? – terdon Jul 14 '14 at 11:19
  • That is not what the question said. Simply. – periket2000 Jul 14 '14 at 11:21
  • Well, no, but what the question said could be done by sed 's/name/abc/' so I think it's safe to assume the situation is a bit more complex than the example shown. – terdon Jul 14 '14 at 11:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.