6

I'm trying to filter this code for the data between <cookie> & </cookie> and the data between account-id=" & " (the trailing quote)

<?xml version="1.0" encoding="utf-8"?>
<results>
 <status code="ok"/>
 <common locale="en" time-zone-id="85">
  <cookie>na3breezfxm5hk6co2kfzuxq</cookie>
  <date>2012-11-11T16:26:52.713+00:00</date>
  <host>http://meet97263421.adobeconnect.com</host>
  <local-host>pacna3app09</local-host>
  <admin-host>na3cps.adobeconnect.com</admin-host>
  <url>/api/xml?action=common-info</url>
  <version>8.2.2.0</version>
  <tos-version>7.5</tos-version>
  <product-notification>true</product-notification>
  <account account-id="1013353222"/>
  <user-agent>curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5</user-agent>
 </common>
</results>

Any help would be appreciated.

EDIT

This is the curl command I run to return the above xml.

curl -s http://meet97263421.adobeconnect.com/api/xml?action=common-info
David Vasandani
  • 1,840
  • 8
  • 30
  • 53

3 Answers3

10

In general, regexes (and therefore grep) aren't well-suited to parsing XML, but if you can guarantee the input is well-formatted and consistent you can do this most easily with grep's perl-style regexes (on systems whose grep has them):

grep -oP '(?<=<cookie>).*?(?=</cookie>)'
grep -oP '(?<=account-id=").*?(?=")'

If you want them in the same command, you can separate them with a |, but then you have to tell which matches which.

grep -oP '(?<=<cookie>).*?(?=</cookie>)|(?<=account-id=").*?(?=")'
Community
  • 1
  • 1
Kevin
  • 53,822
  • 15
  • 101
  • 132
5

As stated by @Kevin regular expressions are ill-suited to parsing XML.

A better approach is to use the xmllint program which apply an xpath expression as follows:

$ xmllint --xpath "string(/results/common/cookie)" data.xml
na3breezfxm5hk6co2kfzuxq

$ xmllint --xpath "string(/results/common/account/@account-id)" data.xml
1013353222
Mark O'Connor
  • 76,015
  • 10
  • 139
  • 185
0

Use these XPath expressions

/results/common/cookie

/results/common/account/@account-id

with a command line XPath interpreter

BeniBela
  • 16,412
  • 4
  • 45
  • 52