How can I remove all script blocks (including multi-line ones) from html files such as:

<script type="text/javascript">
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
(function() {
var gads = document.createElement('script');
gads.async = true;
gads.type = 'text/javascript';
var useSSL = 'https:' == document.location.protocol;
gads.src = (useSSL ? 'https:' : 'http:') +
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(gads, node);

I tried things like this with no success:

sed -i -e 's/<script.*\n.*<\/script>//g' 'path/to/file.html'
  • @mikeserv the answer on the dupe works perfectly for the OP's example here. I have no idea what ..."...span>"... is supposed to be. In any case, this question has already been answered to the OP's satisfaction so, again, there's no point in having them both open. However, there are mechanisms in place for cases where you feel a question has been wrongly closed: i) vote to reopen and ii) bring it up on Unix & Linux Meta.
    – terdon
    Jan 24, 2016 at 21:00

2 Answers 2


Sed processes the input line by line. It's easier in Perl that can process the whole file at once:

perl -0777 -pe 's=<script>.*?\n.*?</script>==sg'
  • -0777 reads the whole file
  • ? after * makes it "frugal", i.e. it matches the shortest possible string.
  • /s makes . match a newline which it normally doesn't.

Note that it can break if the script contains </script> in a comment or quotes. It would be better to parse the HTML.

  • 1
    Thanks a lot. Actually the answer in the question that caused this to be marked as "duplicate" seems to do the job perfectly: perl -0777 -pe 's/<script.*?script>//gs' example.html
    – Sadi
    Jan 24, 2016 at 18:04
  • 1
    @Sadi: It removes single line scripts, too.
    – choroba
    Jan 24, 2016 at 18:07
  • Sorry, my bad, I should have made it clearer...
    – Sadi
    Jan 24, 2016 at 18:20

With sed you can select ranges and delete them:

sed '/<script/,/<\/script>/d' inputfile
  • 1
    This would delete everything before <script on the same line, and similarly for the other end.
    – choroba
    Jan 24, 2016 at 18:08
  • Thanks a lot. Yours looks better than the answer in the question that caused this to be marked as "duplicate". I suggest a minor addition: sed '/<script/,/<\/script>/d' inputfile > outputfile
    – Sadi
    Jan 24, 2016 at 18:09
  • @choroba : THX! It does indeed. So one needs to enclose the range with ^ and $ or better still insert new line before and after when it doesn't exist.
    – Sadi
    Jan 24, 2016 at 18:17
  • Not correct: sed is greedy.
    – Federico
    Oct 29, 2017 at 17:39

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