0

I need help with my sed script. I have a XML-file where I have to remove everything except the text enclosed in these tags:

<TEXT>......</TEXT>
<HEADLINE>......</HEADLINE>

How do I write the sed code ? I know how to remove everything except the text enlosed in ONE tag.

s/.*<TEXT>\(.*\)<\/TEXT>.*/\1/

But how do i write the sed code for many tags ?

1
  • 2
    Why not just use an XML parser?
    – JDB
    Jan 24, 2013 at 20:47

3 Answers 3

1

You can pass multiple commands to sed:

$ echo '<TEXT>Hello</TEXT>
<HEADLINE>there</HEADLINE>' | sed -n 's/.*<TEXT>\(.*\)<\/TEXT>.*/\1/gp; s/.*<HEADLINE>\(.*\)<\/HEADLINE>.*/\1/gp' 
Hello
there

But you really should be careful when applying regex to XML-like files.

1

Assuming that you have valid XML:

sed '/.*<\(TEXT\|HEADLINE\)>\(.*\)<\/\(TEXT\|HEADLINE\)>.*/!d;s//\2/' yourfile.xml

If you want to use a sed script add this line:

/.*<\(TEXT\|HEADLINE\)>\(.*\)<\/\(TEXT\|HEADLINE\)>.*/!d;s//\2/

Then run:

sed -f yourscript.sed < yourfile.xml
2
  • But how do add this to a script file ?
    – mrjasmin
    Jan 24, 2013 at 21:02
  • @mrjasmin I added that part to my answer.
    – speakr
    Jan 24, 2013 at 21:31
0

This might work for you (GNU sed):

 sed -r '/<(text|headline)>/I!d;s//&\n/;s/^[^\n]*\n//;:a;/<\//!{$!{N;ba}};s/\n/ /g;s/<\//\n&/;P;D' file

This removes all text accept that which is between TEXT and HEADLINE tags and on multi-line values replaces newlines with spaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.