0

I need a perl/shell script which will replace all the occurences of below HTML code within all the files with text:

<? test_routine ?>

HTML code

<tr>
  <td>
    <label>testlabel</label>
  </td>
</tr>

This HTML code can occur with any number of spaces i.e

<tr><td><label>testlabel</label></td></tr> 

is also a valid search criteria (i.e ignore all the spaces)

Can any one please let me know how i can resolve this using perl/shell script. Thank you.

1

1 Answer 1

1

Here's one line of perl that will do what you need using a regular expression:

$html =~ s/<\s*tr\s*>\s*<\s*td\s*>\s*<\s*label\s*>\s*testlabel\s*<\s*\/label\s*>\s*<\s*\/td\s*>\s*<\s*\/tr\s*>/<? test_routine ?>/gi
10
  • 1
    On order to handle matches spanning multiple lines, wrap this in a script which reads the entire file at once, and add a /m modifier to the substitution. perl -0777 -pe 's%from%to%mg'
    – tripleee
    Aug 6, 2011 at 16:55
  • Actually, the /m modifer isn't needed in this case. You're right, though, the whole file has to be read into the $html variable before this line is run. Aug 6, 2011 at 16:59
  • I printed $html and I'm able see the replaced text. Thanks for that. But how to write this back to the file?. I tried with open outfile, ">test.html";print (outfile "$html");
    – progster
    Aug 11, 2011 at 18:57
  • That depends. Could you give a bit more details on how the file is loaded? Aug 11, 2011 at 18:58
  • my $file = "test.html"; my $a1 = do {local $/ = undef; open my $html, "<", $file; <$a1>}; close $a1;...followed with your statement above...and with my statement above..
    – progster
    Aug 11, 2011 at 19:01

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.