Comments On: How to Find and Replace text across 20,000 files


I have a feeling it didn't work

Posted Nov 12, 2008
by Tom Legrady

In the first invocation of perl, you search for:

an opening angle bracket '<', followed by the upper case or lower case characters 'H', 'T', 'M', 'L', followed by any number of any character, followed by a closing angle bracket.

What you really want is not any number of any character, but rather, any number of any character other than a closing angle bracket: s/]*>//. [..] is a character set, for exchample, [abc] matches an 'a', or a 'b', or a 'c'. [a-z] matches any one lower case character. [^>] matches anything other than a closing angle bracket. The star after it makes it match zero or more times. In this case, your code is wrong, and you probably had to go do a lot of fixing ... assuming you had backed things up before you damaged them.

You do one search for
You search the entire directory hierarchy 12 times .. you could collapse the first 11 of those into a single call using multiple expressions

perl -0777 -pi -e's///gi' -e's/\t*//gi' -e...

or, for that matter, just because -e is pronounced expression doesn't mean you're not allowed to put a whole bunch of statements in there:

perl -077 -pi -e's///gi; s/\t*//gi;m ...'

That is, open the file, do the first search-and-replace, do the second search-and-replace, do the....

Sorry, but you're wrong about

's/\t*(.*)<\/TITLE>//gi'

For one thing, that .* will swallow up everything until the end of file. You want to search for everything until the next opening angle bracket. The parentheses around that cause the matched characters to be saved in a temporary variable, '$1', true enough, but everything matched in the 'search' part of the search-and-replace is replaced with the replace part of the search-and-replace. That's why it's called search-and-replace. So you have to use '$1' as the replace portion ...

's/\t*([^<]*)<\/TITLE>/$1/gi'

The biggest mistake is not using the Perl Monk community to help you figure out what you need. http://www.perlmonks.org is the place to go with your newbie questions, and with a minimum of ridicule or torment they'll turn you into newbie-no-more.

Tom



Add Your Comment:
Title:
Name:
Email:
Comment:


Enter the Text from the Captcha Image