Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have some huge xml text files. I need to write a script to find and print a specific tag only. I tried sed and grep but they both return the whole line.

Using SunOS 5.x, so not all linux commands may work. grep -o is not available.

The 'xml' file is not actually one huge xml document, but each line is a separate xml document, with just a few tags, not even nested. And the structure is fairly easy, so full xml parsers is not needed, and probably would not work.

I was looking for sed, awk, or some other one liners, but could not get them to work, and they are both relatively new to me.

share|improve this question
    
If you show an example line and the sed command you tried, we can come up with a sed command that should do the job. – Dennis Williamson Feb 9 '11 at 15:43
up vote 2 down vote accepted

You should use a tool that's made for parsing XML files, however here is an example of how you might do that in sed:

Given a simple line like <foo>bar</foo><baz>qux</baz> and you want the value "bar" you can do this:

sed -e 's|.*<foo>\([^<]*\)</foo>.*|\1|' inputfile
share|improve this answer
    
Exactly what I need. – Ayman Feb 10 '11 at 5:45

Use the 'xml sel' command of xmlstarlet: http://xmlstar.sourceforge.net/

Example:

xml sel -t -c '/xpath/to/my/tag' xmlfile.xml

Beware of default namespace in your xml file though (read this). An example:

xml sel -N x="http://www.mozilla.org/2006/browser/search/" -t -m '//x:Param' -c "." -n /usr/lib/firefox-3.5/searchplugins/google.xml

I use xmlstarlet for all xml tasks now, mostly queries.

share|improve this answer
    
unfortunately I'm not permitted to install third party. And the script should be usable on any SunOS system without installing new progs – Ayman Feb 10 '11 at 5:43
$ echo '<a><b>B</b><c>C</c></a>' > file.xml
$ perl -ne 'm!<b>(.*)</b>! && print "$1\n"' *.xml
B

$ perl -ne 'BEGIN{$/="<"}; print "$1\n" if m![bc]>([^<]+)<!' *.xml
B
C

But really you should use an XML parser for reasons that should be (or will become) all too obvious.

share|improve this answer

Two ideas:

  1. install grep from sunfreeware.com. This should get you the -o option that you know from linux.

  2. write a perl or python script to do the job.

share|improve this answer
    
unfortunately I'm not permitted to install third party. And the script should be usable on any SunOS system without installing new progs. – Ayman Feb 10 '11 at 5:43
    
check and see if you got perl or python installed. Then a script written by yourself should be pretty portable. – Isaac Feb 10 '11 at 10:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .