1

Can any please help me to write the shell script to find the value from the below xml:-

<?xml version="1.0" encoding="UTF-8"?>
<log>
<logentry revision="36">
    <author>XYZ</author>
    <date>2014-07-15T14:47:18.328479Z</date>
    <paths>
        <path action="A" localPath="ABC" kind="unknown">/branches/ABC</path>
        <path action="A" localPath="ABC" kind="unknown">/branches/ABC</path>
        <path action="M" localPath="DEF" kind="unknown">/branches/CDF</path>
        <path action="M" localPath="DEF" kind="unknown">FRG</path>
    </paths>
    <msg>added</msg>
</logentry>
</log>

I want to extract the value of the localPath i.e "ABC" and "DEF" as output and write in one file.

1
  • BTW, do you really have two adds, and then two different modifications, of the exact same file? I wonder if the perceived need for a sort -u step is an artifact of your anonymization, rather than something that could ever happen with the genuine data. Commented Jul 15, 2016 at 16:30

2 Answers 2

2

Use an XML-aware tool. For example:

$ xmllint --xpath '/log/logentry/paths/path/@localPath' file.xml 

Output:

 localPath="ABC" localPath="ABC" localPath="DEF" localPath="DEF"

which you can further process

$ xmllint --xpath '/log/logentry/paths/path/@localPath' file.xml \
  | sed 's/"/\n/g;' \
  | grep -v '^ ' \
  | sort -u

to get

ABC
DEF

or using xsh

open file.xml ;
$h := hash @localPath /log/logentry/paths/path ;
for { keys %$h } { echo (.) ; }

Output:

ABC
DEF
Sign up to request clarification or add additional context in comments.

4 Comments

Is the output format for xmllint --xpath documented with strong enough guarantees to make the following string manipulation forwards-compatible?
@CharlesDuffy: I don't know, that's why I included the output here, too.
@choroba:Thanks for your reply. I tried to run the command xmllint --xpath '/log/logentry/paths/path/@localPath' file.xml ,but it seems --xpath is not available. It is giving me error unknown option --xpath. Can you please tell me to fix this or do I need to use any other option.?
@user6376225: You can try upgrading xmllint.
1

...or, with XMLStarlet:

xmlstarlet sel -t -v /log/logentry/paths/path/@localPath -n

...emitting:

ABC
ABC
DEF
DEF

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.