0

I need help for some command for handle the following situation. I search on net for help but i can't succeed to find solution.

Problem is:

I have a xml file named as "temp.xml" The text in the xml file is for example

<?xml version="1.0" encoding="utf-8"?>
<NoteData Note_Nbr="312" Data_Revision="2" Note_Revision="1" />

I want to save only Note_Nbr to my variable x (312)

I try a something but it doesn't work.

 X=$(sed  -r  's/[^|]*(Note_Nbr=")(\d\d\d)([^|]*)/2 /' temp.xml )

Thank you for your helps.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Umut Dönmez
  • 3
  • 1
  • 2

1 Answers1

1

The right way to do this is with a real XML parser:

x=$(xmllint --xpath 'string(/NoteData/@Note_Nbr)' test.xml)

...or, if you have XMLStarlet rather than a new enough xmllint:

x=$(xmlstarlet sel -t -m '/NoteData' -v @Note_Nbr -n <test.xml)

See also this answer: https://stackoverflow.com/a/1732454/14122

Now, if you only wanted to work with literal strings, you could build something fragile that looked like this, using parameter expansion:

s='<NoteData Note_Nbr="312" Data_Revision="2" Note_Revision="1" />'
s=${s#* Note_Nbr=\"}; s=${s%%\"*}; echo "$s"

Alternately, you could use native regular expression support within bash (note that this functionality is a bash extension not present in POSIX sh):

s='<NoteData Note_Nbr="312" Data_Revision="2" Note_Revision="1" />'
re='Note_Nbr="([^"]+)"'
if [[ $s =~ $re ]]; then
  match="${BASH_REMATCH[1]}"
else
  echo "ERROR: No match found" >&2
fi
Community
  • 1
  • 1
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • Thank you for your response. When i try this command it gives me an error Unknown option --xpath – Umut Dönmez Jul 07 '12 at 15:38
  • @UmutDönmez Unfortunately, older versions of xmllint don't have `--xpath`; this is why I also provided the xmlstarlet version. I'm glad this was helpful. – Charles Duffy Jul 07 '12 at 16:37