SW to replace a string in Windows

Posted on

QUESTION :

I have a text file (actually XML) that I want to be able to change using a command line. In other words, as part of a Windows batch, I want to locate a string (in this case @@@@, which uses a character not present anywhere else in the file), and then replace it with something simple, such as a date ‘8/18/11’.

Is there some kind of ‘grep’, ‘perl’ or other type of way to, in short order, just replace the string — again, this has to be via the command line, since I want to automate the process.

Incidentally, I have Active State PERL on my PC.

ANSWER :

To replace all the occurrences of findthis with replaceto in the file example.txt do:

perl -pi -e 's/findthis/replaceto/g' example.txt 

There is nothing wrong with the answers that you already have, but just to add to the options I will point out that if you are on Windows 7, you have powershell installed as well. Or for that matter it could be installed on XP/Vista if you so choose. Then:

$foo = gc C:PathToFile.txt; $foo | %{$_.replace('@@@@', '8/1/11')} | Out-File C:PathToFile.txt

You seem to know grep. You may want to use the same utility which is available for windows. You do not need to install it but only have to put it within the path (or in the same folder where the batch file is executed). If you use it, do not forget to download the “dependencies” as well as the binary files (or download the installation exectuable file if you like that sort of thing).

Alternatively, you may want to use VBS language (scripting language for Windows XP) and create a script to replace a string in a file (see this link for details) and running the script from the command line using cscript

Leave a Reply

Your email address will not be published.