0

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?

tod
  • 1,539
  • 4
  • 17
  • 43
user2800089
  • 2,015
  • 6
  • 26
  • 47
  • 5
    Using a XML parser might be a better option. – devnull Apr 28 '14 at 12:44
  • exact the use case of xpath. if you need to wrap it with a shell script, you could use the tool `xmllint` with `--xpath`. I cannot suggest further before seeing your document structure. Don't try to use awk/sed/grep on a xml, if you want your script to be stable. well you could use those though, for a quick and dirty shot/test. – Kent Apr 28 '14 at 12:52
  • 2
    XML is not a regular language, which means you cannot match its structures with regular expressions effectively. – Alexei Averchenko Apr 28 '14 at 14:14
  • See [Grep and Sed Equivalent for XML Command Line Processing](http://stackoverflow.com/questions/91791/grep-and-sed-equivalent-for-xml-command-line-processing) – Cristian Ciupitu Apr 28 '14 at 19:01

4 Answers4

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.

1

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
Jotne
  • 40,548
  • 12
  • 51
  • 55
1

You can use this sed,

sed -n '/LANGUAGE/{N; s/.*<string>\(.*\)<\/string>.*/\1/p; }' Locale.xml
sat
  • 14,589
  • 7
  • 46
  • 65
0

Using xsh:

open file.xml ;
echo //void[string="LANGUAGE"]/string[2]
choroba
  • 231,213
  • 25
  • 204
  • 289