3

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.

1
  • 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. Feb 9, 2011 at 15:43

4 Answers 4

2

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
1
  • Exactly what I need.
    – Ayman
    Feb 10, 2011 at 5:45
2

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.

1
  • 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, 2011 at 5:43
2
$ 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.

1

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.

2
  • 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, 2011 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, 2011 at 10:19

You must log in to answer this question.

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