开发者

What command should be used to get text from a line of an XML file on linux?

开发者 https://www.devze.com 2023-02-21 22:12 出处:网络
I have a text file and from that file i have to get specific text. What command should be used to get it?

I have a text file and from that file i have to get specific text. What command should be used to get it?

e.g. file text is as follows:

<name>this is first line</name>
<name>thi开发者_运维百科s is second line</name>
<name>this is third line</name>

I have to get only text from these tags, i.e. i need "this is first line".


Assuming that it is actually a full xml document, you might (should) prefer

xmllint -xpath '//name/text()' test.xml

Or if you want to have newlines, you can

xsltproc.exe trafo.xslt test.xml

with trafo.xslt like

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="/">
        <xsl:for-each select="//name[text()]">
            <xsl:if test="text()">
                <xsl:value-of select="text()"/>
                <xsl:text>&#x0a;</xsl:text>
            </xsl:if>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>


Sehe's answer doesn't add newlines between the lines. I'd suggest using the following instead:

xmlstarlet sel -t -m '//name/text()' -v '.' -n  test.xml
#              ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^ ^^^
#              for each xpath match    |     |
#                          print the result  |
#                         followed by a newline

or

xmlstarlet sel -t -m '//name' -v 'text()' -n  test.xml
#               ^^^^^^^^^^^^^ ^^^^^^^^^^^ ^^^
#          for each name tag       |       |
#    print the text that's inside it       |
#                         followed by a newline

(they behave a little differently regarding where they print newlines)


I believe you need all the text inside the <name> tags 1 line per tag.

grep -Po "(?<=<name>)[^<]*(?=</name>)" yourfile

The result will be

this is first line
this is second line
this is third line


Ruby(1.9+)

$ ruby -ne 'puts $_.scan(/<name>(.*?)<\/name>/)' file
this is first line
this is second line
this is third line

awk

$ awk 'BEGIN{ RS="</name>" }/<name>/{ gsub(/.*<name>/,"");print }' file
this is first line
this is second line
this is third line

sed

$ sed -r 's|<name>(.[^>]*)</name>|\1|' file
this is first line
this is second line
this is third line


grep will help you find the right lines. If it is formatted regularly, maybe you can use cut to remove the <name> tags? If it's not, then sed is probably the right tool for the job.


Is this would work for you ? (not sure to understand your need) :

cat yourfile | grep "this is first line"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号