Eu preciso fazer isso usando o 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>
Eu 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á em marca de ficção com atributo b sozinho. Por favor, ajude-me com isso usando script ou comando shell do Unix. Obrigado !
Se você quer apenas substituir <author type=''><\/author>
por <author type='Local'><\/author>
, você pode usar o comando sed
:
sed "/<fiction type='a'>/,/<\/fiction>/ s/<author type=''><\/author>/<author type='Local'><\/author>/g;" file
Mas, ao lidar com xml, eu recomendo um analisador/editor xml como xmlstarlet :
$ 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 sinalizador -L
para editar o arquivo inline, em vez de imprimir as alterações.
Poderíamos usar um xsl-document doThis.xsl
e processar o source.xml
com xsltproc
em um newFile.xml
.
O xsl é baseado na resposta a este pergunta .
Coloque isso em um arquivo doThis.xsl
<?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 o newFile.xml
$: xsltproc -o ./newFile.xml ./doThis.xsl ./source.xml
Este será o newFile.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 a ficção do tipo b é XPath
.
É muito fácil com sed
. O script a seguir alterará o conteúdo do arquivo a.xml
e colocará o original em a.bak
como backup.
O que ele faz é procurar cada arquivo pela string <author type=''>
e substituí-lo por <author type='Local'>
. O modificador /g
significa que ele tentará fazer mais de 1 substituição em cada linha, se possível (não necessário para o arquivo de exemplo).
sed -i.bak "s/<author type=''>/<author type='Local'>/g" a.xml
xmlstarlet edit --update "/book/fiction[@type='b']/author/@type" --value "Local" book.xml