GP SoftwareTwitter
Opus FAQsManualCommandsObjects

Search and Replace File Text Using Perl Regex

This button uses Perl to do the replacement for you. It does require that you have Perl installed, which you can get for free, I chose to use ActivePerl, but there are several options out there. Here is the link for ActivePerl http://www.activestate.com/activeperl/

The way I use it is to find all of the files whose content has something that I need to change. Then with the "Find Results" collection open I just select all and then press the button (see code below), it will first prompt you for what you want to replace, then what you want to replace it with. Since this is Perl both source and replacement text have to be the form of a Regular Expression, so it may not be easy for beginners, but it allows a LOT of flexibility for those who already know regex.

Finally, it also creates a backup of the original document and suffixes it with ".bak". If after the command is finished you are satisfied with the results, you can delete the ".bak" files, which if you did it right, should now be selected in the updated "Find Results" collection.

The button code is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<usercommand backcol="none" textcol="none">
	<label>PerlReplace</label>
	<tip>Perl script which will replace a source string with a replacement string for all selected files</tip>
	<icon1>#script</icon1>
	<function type="batch">
		<instruction>@filesonly</instruction>
		<instruction>@useactivelister</instruction>
		<instruction />
		<instruction>@set from = {Rs|Enter source string (cancel to abort):}</instruction>
		<instruction>@set to = {Rs|Enter replacement string:}</instruction>
		<instruction />
		<instruction>perl -pi.bak -e s/{$from}/{$to}/g {filepath$} </instruction>
		<instruction>@nodeselect </instruction>
	</function>
</usercommand>
1 Like

For those, who do not want a backup file to be created, just remove the .bak from the command line in

perl -pi.bak -e s/{$from}/{$to}/g {filepath$},

making it

perl -pi -e s/{$from}/{$to}/g {filepath$}.

Just note, that this removed any security measures @sdct989 has added.

If you do not want the cmd.exe window to pop up briefly, then place this @runmode:hide in the line above the perl command, making it:

<?xml version="1.0"?>
<button backcol="none" display="both" textcol="none">
	<label>Replace text...</label>
	<tip>Replaces given text with given replacement text in all selected files.</tip>
	<icon1>#edit</icon1>
	<function type="batch">
		<instruction>@filesonly</instruction>
		<instruction>@useactivelister</instruction>
		<instruction />
		<instruction>@set from = {Rs|Enter source string (cancel to abort):}</instruction>
		<instruction>@set to = {Rs|Enter replacement string:}</instruction>
		<instruction />
		<instruction>@runmode:hide</instruction>
		<instruction>perl -pi -e s/{$from}/{$to}/g {filepath$}</instruction>
	</function>
</button>