问题
I have one xml file as below, I need "en" using some unix command.
<void method="put">
<string>LANGUAGE</string>
<string>en</string>
</void>
using below command (got from some link in google),
sed -n '/string/{s/.*<string>//;s/<\/string.*//;p;}' Locale.xml
I am getting output as
LANGUAGE
en
so I used
sed -n '/string/{s/.*<string>//;s/<\/string.*//;p;}' Locale.xml | tail -1
But is there any option in sed by which I can get second value only?
回答1:
You can use this sed
,
sed -n '/LANGUAGE/{N; s/.*<string>\(.*\)<\/string>.*/\1/p; }' Locale.xml
回答2:
Use xmlstarlet.
$ cat x.xml
<?xml version="1.0"?>
<void method="put">
<string>LANGUAGE</string>
<string>en</string>
</void>
$ xmlstarlet sel -t -c '/void/string[2]/text()' x.xml
en
Or use xmllint.
$ xmllint --xpath '/void/string[2]/text()' x.xml
en
More about XPath.
回答3:
You can search for LANGUAGE
and the print next line:
awk -F"[<>]" '/LANGUAGE/ {getline;print $3}' Locale.xml
en
Or search for string
and print the last one:
awk -F"[<>]" '/string/ {f=$3} END {print f}' Locale.xml
en
回答4:
Using xsh:
open file.xml ;
echo //void[string="LANGUAGE"]/string[2]
来源:https://stackoverflow.com/questions/23341361/how-to-read-xml-file-in-linux