Take the 2-minute tour ×

I have the following piece of code that is repeated in several files:

    <th scope="row"> (some php code) </th>
         (more php and html)

There may be some whitespace before/after tr, th or td tags.

What tool and regex shall I use in order to replace it with the following:

<div class="row">


share|improve this question
add comment

3 Answers

up vote 3 down vote accepted

Perl has a -0777 command line option to let you read the whole thing into memory. Once you’ve done that, you can use a substitution that uses \s* for whitespace and it will cross newline boundaries. If you use ., make sure to use /s on the end of the substitution.

I can’t really tell what you want to match, but the general principle is:

perl -0777 -i.orig -pe 's/foo/bar/gs' file1 file2 file3
share|improve this answer
add comment

For the ∞th time, do not use regex to parse HTML. Use an HTML parser.

In perl, that means using a module such as Web::Scraper.

share|improve this answer
I have a special dispensation. :) –  tchrist Apr 23 '11 at 20:20
This was a one-time thing, so I was looking for the shortest solution possible. Otherwise I wouldn't have done it with a regex :) –  Nikolay Yordanov Apr 23 '11 at 20:26
add comment

you can do this will awk as well. First set record separator to </tr>, then find the opening tag <tr> as well as the search string. Let's say your search string is "more html code".

v="my new string"
awk -vRS="</tr>" -v newstring="$v" '/<tr>/ && /more html code/{ $0=newstring}{print $0>FILENAME}' file 

Another alternative to Perl, similar to your accepted answer

share|improve this answer
add comment

Your Answer


