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?

4
  • 5
    Using a XML parser might be a better option.
    – devnull
    Apr 28, 2014 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, 2014 at 12:52
  • 2
    XML is not a regular language, which means you cannot match its structures with regular expressions effectively. Apr 28, 2014 at 14:14

4 Answers 4

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 use this sed,

sed -n '/LANGUAGE/{N; s/.*<string>\(.*\)<\/string>.*/\1/p; }' Locale.xml
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
0

Using xsh:

open file.xml ;
echo //void[string="LANGUAGE"]/string[2]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.