1

I want to write a script that completely removes every instance of a particular span class from a given HTML file.

For example, if my undesired span class is "foo" then running my script on the file

<html>
  <head>
    <title>hello world</title>
  </head>
  <body>
lorem ipsum
<span class="foo"> STUFF </span>
alpha beta <span class="foo"> MORE 
STUFF</span>
  </body>
</html>

should yield

<html>
  <head>
    <title>hello world</title>
  </head>
  <body>
lorem ipsum
alpha beta 
  </body>
</html>

I have two questions.

  1. Can this be done with sed or perl?
  2. Is there a tool in linux that is designed to easily edit HTML documents like this?
  • What about <span class="bar foo">, possibly with a linebreak in it, and nested spans in your to-be-deleted range? General-case HTML manipulation is hard-to-impossible with regular-expression tools like sed, XSLT might be an approach with at least a different set of problems. – Ulrich Schwarz Aug 24 '15 at 19:37
3

Perl can do it, even across line breaks.

Dump this into a file (I'll call it example.html):

<p>Here is some <span>foo bar</span> example text.</p>
<p>Some text even <span>foo
bar</span> spans across line breaks.</p>

Then try it out:

$ perl -0777 -pe 's/<span.*?<\/span>//gs' example.html
<p>Here is some  example text.</p>
<p>Some text even  spans across line breaks.</p>
  • Wouldn't be safer to modify this command as perl -0777 -pe 's/<span.*?<\/span>//gs' example.html to make sure that end of range is </span>? – Sadi Jan 27 '16 at 10:45
  • Yes, you make a good point. I'll edit the answer to reflect your improvement. – Klaatu von Schlacker Mar 12 '17 at 8:06
  • 1
    Actually there are problems with the Perl code. What happens when </span> falls at the end of line, like as in the OP's case? And more importantly, this will not handle the case of nested <span>. – user218374 Mar 12 '17 at 8:26
3

Provided your HTML is well formed XML you can do this with an XML processing tool such as xmlstarlet. Assuming the file is original.html:

xmlstarlet ed -O -d '/html//span[@class = "foo"]' original.html

Output

<html>
  <head>
    <title>hello world</title>
  </head>
  <body>
lorem ipsum

alpha beta
  </body>
</html>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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