
Ich muss dies mit einem Unix-Skript oder -Befehl tun. Es gibt eine XML-Datei in /home/user/app/xmlfiles wie
<book>
<fiction type='a'>
<author type=''></author>
</fiction>
<fiction type='b'>
<author type=''></author>
</fiction>
<Romance>
<author type=''></author>
</Romance>
</book>
Ich möchte den Autorentyp in der Belletristik als lokal bearbeiten.
<fiction>
<author type='Local'></author>
</fiction>
Ich muss den Autortyp ändern, der inFiction-Tag mit Attribut ballein. Bitte helfen Sie mir dabei mit einem Unix-Shell-Skript oder -Befehl. Danke!
Antwort1
<author type=''><\/author>
Wenn Sie nur durch ersetzen möchten <author type='Local'><\/author>
, können Sie diesen sed
Befehl verwenden:
sed "/<fiction type='a'>/,/<\/fiction>/ s/<author type=''><\/author>/<author type='Local'><\/author>/g;" file
Aber wenn Sie mit XML arbeiten, empfehle ich einen XML-Parser/Editor wiexmlstarlet:
$ 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>
Verwenden Sie das -L
Flag, um die Datei inline zu bearbeiten, anstatt die Änderungen auszudrucken.
Antwort2
xmlstarlet edit --update "/book/fiction[@type='b']/author/@type" --value "Local" book.xml
Antwort3
Wir könnten ein XSL-Dokument verwenden doThis.xsl
und es source.xml
in xsltproc
ein verarbeiten newFile.xml
.
Das XSL basiert auf der Antwort auf dieseFrage.
Legen Sie dies in eine doThis.xsl
Datei
<?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>
Jetzt produzieren wir dienewFile.xml
$: xsltproc -o ./newFile.xml ./doThis.xsl ./source.xml
Das wird dasnewFile.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>
Der zum Suchen nach Belletristik des Typs B verwendete Ausdruck lautet XPath
.
Antwort4
Mit ist das ganz einfach sed
. Das folgende Skript ändert den Inhalt der Datei a.xml
und legt das Original a.bak
als Backup an.
Es durchsucht jede Datei nach der Zeichenfolge <author type=''>
und ersetzt sie durch <author type='Local'>
. Der /g
Modifikator bedeutet, dass nach Möglichkeit mehr als eine Ersetzung pro Zeile versucht wird (für Ihre Beispieldatei nicht erforderlich).
sed -i.bak "s/<author type=''>/<author type='Local'>/g" a.xml