1

I'm trying to pass a variable to sed that contains XML.

From this XML I would like to extract the parts contained between <image_viewer> </image_viewer> ; and <image_thumb_url> </image_thumb_url>

There is an HTML link between each of those tags, which has no spaces; and each tags + link are on a single line.

It seems I'm doining it completely wrong, I'm very new to bash...

base64 -w0 "$1" > "$1".64.jpg

apiXml=$(curl -v -F "upload=<$1.64.jpg" -F key="$apiKey" -F format=xml "$apiUrl")

imgView=$(echo "$apiXml" | sed 's/<image_viewer>\(.*\)<\/image_viewer>/\1/')
imgThumb=$(echo "$apiXml" | sed 's/<image_thumb_url>\(.*\)<\/image_thumb_url>/\1/')

imgLink="[url=$imgView][img]$imgThumb[/img][/url]"

echo "$imgLink"

Any suggestions would be welcome, thanks !

yaka
  • 107
  • 2
  • 6
  • Your `sed` looks fine to me. Can you edit your expected and actual output into the question? Also, have you tried saving the XML to a file and running `sed` on that? – ThisSuitIsBlackNot Oct 02 '13 at 17:35
  • I would like to do it without saving to file if it's possible, so I didn't try saving to file yet. My output is the entire XML file on each sed command it seems, and the final echo just gives [url=][img][/img][/url], so it pretty much outputs nothing from the sed. I would like to have the links included in the XML to be extracted and put between the [url.../url] tags. – yaka Oct 02 '13 at 17:37
  • I didn't mean you need to change your program to write to a file, I meant as a troubleshooting step. `sed 's/foo/bar/'` will output a line for every line of input it gets, so if your XML is 500 lines long, the output of `sed` will also be 500 lines long. – ThisSuitIsBlackNot Oct 02 '13 at 17:45
  • See also related http://stackoverflow.com/a/1732454/14122 – Charles Duffy Oct 02 '13 at 17:46

1 Answers1

2

It's easier to just use the right tool for the job here.

read imgView < <(xmlstarlet sel -t -m '//image_viewer' -v . -n <<<"$apiXml")
read imgThumb < <(xmlstarlet sel -t -m '//image_thumb_url' -v . -n <<<"$apiXml")

Any XPath engine will do -- XMLStarlet is just one of many.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441