1

I'm trying to adapt the following script to take input from a text file on my computer "input.txt" and output the result to a text file "output.txt".

The script works fine on grabbing html from the internet but I can't figure out the adaptation I need.

Strange thing is I figured it out a year ago - but I can't remember what I did - I'm not a programmer.

Code:

url='http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags'
curl -s  "$url"   |
sed -Ene:n -etD   \
    -e's/ ?[^ "]*"[^"]*"//g;/"/'bN  \
    -e's/[[:space:]]*($|<)/\n\1/'   \
    -e'/^Moderator.s Note/q'        \
    -e'/.\n/P;/\n</!t'        -e:D  \
    -e'/\n/D;/^<script>/!s/>/&\n/'  \
    -e'/\n/!s/<\/script>/\n/' -e:N  \
    -e'/\n/!{N;s///;}' -e//tD -etn

1 Answer 1

2

How to remove javascript from html files and leaving plain text?

Its an interesting question, in that I think it highlights another issue with using regex for parsing markup, maintainability.

If you have php available on your system this script will do it

#!/usr/local/bin/php
# point the #! to wherever your PHP commandline binary is

<?php

error_reporting(1);

$html = file_get_contents('http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags');

// create an object representing the DOM tree of the webpage
$document = new DOMDocument;
$document->loadHTML($html);

// store the <script> elements as a DOMN
$script_nodes = $document->getElementsByTagName('script');

// For some reason you can't use the DOMNode::removeChild method
// when iterating through an instance of PHP's DOMNodeList
// so use an array to queue the values in. see
// http://php.net/manual/en/domnode.removechild.php
$scripts_to_remove = [];
for ( $i=0; $i < $script_nodes->length; $i++ ) {
    $scripts_to_remove[] = $script_nodes->item($i);
}

// now we can iterate through the <script> nodes removing them
foreach ( $scripts_to_remove  as $s_node ) {
    $parent = $s_node->parentNode;
    $parent->removeChild($s_node);
}

// print out the new DOM as HTML
echo $document->saveHTML();

Usage

To use the script, setup a file containing the above code, make it executable, run it and redirect the output into a file, the file should contain the HTML stripped of the <script> tags.

You must log in to answer this question.

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