Forum Moderators: coopster

Message Too Old, No Replies

Search Replace Script for update

         

hawkeye44

8:28 pm on Jun 8, 2010 (gmt 0)

10+ Year Member



I'd like to use a script to update the information in a large batch of technical documents in a directory and save myself a real pain in the butt of going through a couple thousand files.

So I'd be searching for say Alberto and replacing with Sam in every document, and also searching in the same documents for email addresses, A-Berto@example.com and replacing it with new address Sam-t@example.com. Also it needs to be global, every time Alberto comes up it needs to be replaced with Sam. I need to update parent company, phone numbers, etc etc, stinks.

Scripts are awesome for such things.

Help?

[edited by: jatar_k at 8:42 pm (utc) on Jun 8, 2010]
[edit reason] examplified [/edit]

Alcoholico

8:44 pm on Jun 8, 2010 (gmt 0)

10+ Year Member



I think it is against the forum TOS to recommend or even mention specific products, so I do not, but I do know several freeware text editors with multi-replace capabilities you could use to search and replace in multiple documents at a time, no need for a custom script.

hawkeye44

8:54 pm on Jun 8, 2010 (gmt 0)

10+ Year Member



Freeware text editors do single replaces, I have yet to run into a multi-replace and specifically one that will retain the values I wish to replace, hence why a script which remembers what values I want to apply each time would work better. I need something that can be used for imported data I want to export as well. Just need to replace a items that are in every last document.

Tommybs

9:07 pm on Jun 8, 2010 (gmt 0)

10+ Year Member



Hi,

I don't know of a free script to do it but could you not knock something up yourself if there are only a few things that need replacing?
This isn't tested by the way it's off the top of my head so test it somewhere first on non-critical data.

function myreplace($find, $replace, $src){
$src = str_replace($find, $replace, $src);
return $str;
}
if ($handle = opendir('/path/to/files')) {
while (false !== ($file = readdir($handle))) {
$contents = file_get_contents("/path/to/files/$file");
$contents = myreplace("replace@email.com", "me@mail.com", $contents);
$h = fopen("/path/to/files/$file", "w");
fwrite($h, $contents);
fclose($h);

}
closedir($handle);
}
?>

Hope this helps

T

Tommybs

9:11 pm on Jun 8, 2010 (gmt 0)

10+ Year Member



The issue with the above code I posted actually is it could potentially replace substrings of full words that match (e.g sam in samantha). You can pass in an array of matches and replacements though in str_replace. The other option is of course to replace the str_replace with a regular expression.