
Eu preciso fazer isso usando um script ou comando unix. Existe um arquivo xml em /home/user/app/xmlfiles como
<book>
<fiction type='a'>
<author type=''></author>
</fiction>
<fiction type='b'>
<author type=''></author>
</fiction>
<Romance>
<author type=''></author>
</Romance>
</book>
Quero editar o tipo de autor na ficção como local.
<fiction>
<author type='Local'></author>
</fiction>
Preciso alterar o tipo de autor que está emtag de ficção com atributo bsozinho. Por favor me ajude com isso usando script ou comando shell unix. Obrigado !
Responder1
Se você quiser apenas substituir <author type=''><\/author>
por <author type='Local'><\/author>
, você pode usar esse sed
comando:
sed "/<fiction type='a'>/,/<\/fiction>/ s/<author type=''><\/author>/<author type='Local'><\/author>/g;" file
Mas, ao lidar com xml, recomendo um analisador/editor de xml comoxmlstarlet:
$ xmlstarlet ed -u /book/*/author[@type]/@type -v "Local" file
<?xml version="1.0"?>
<book>
<fiction>
<author type="Local"/>
</fiction>
<Romance>
<author type="Local"/>
</Romance>
</book>
Use o -L
sinalizador para editar o arquivo embutido, em vez de imprimir as alterações.
Responder2
xmlstarlet edit --update "/book/fiction[@type='b']/author/@type" --value "Local" book.xml
Responder3
Poderíamos usar um documento xsl doThis.xsl
e processá-lo source.xml
em xsltproc
um arquivo newFile.xml
.
O xsl é baseado na resposta a estapergunta.
Coloque isso em um doThis.xsl
arquivo
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="UTF-8" omit-xml-declaration="no"/>
<!-- Copy the entire document -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- Copy a specific element -->
<xsl:template match="/book/fiction[@type='b']/author">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<!-- Do something with selected element -->
<xsl:attribute name="type">Local</xsl:attribute>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Agora produzimos onewFile.xml
$: xsltproc -o ./newFile.xml ./doThis.xsl ./source.xml
Este será onewFile.xml
<?xml version="1.0" encoding="UTF-8"?>
<book>
<fiction type="a">
<author type=""/>
</fiction>
<fiction type="b">
<author type="Local"/>
</fiction>
<Romance>
<author type=""/>
</Romance>
</book>
A expressão usada para encontrar ficção do tipo b é XPath
.
Responder4
É bem fácil com sed
. O script a seguir alterará o conteúdo do arquivo a.xml
e colocará o original a.bak
como backup.
O que ele faz é procurar a string em cada arquivo <author type=''>
e substituí-la por <author type='Local'>
. O /g
modificador significa que tentará fazer mais de uma substituição em cada linha, se possível (não é necessário para o seu arquivo de exemplo).
sed -i.bak "s/<author type=''>/<author type='Local'>/g" a.xml