SW to replace a string in Windows

2

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.

Rolnik

Posted 2011-08-19T13:27:54.183

Reputation: 1 457

Answers

5

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

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

Nifle

Posted 2011-08-19T13:27:54.183

Reputation: 31 337

On Windows you should normally use " not ' to enclose argument strings. – RedGrittyBrick – 2011-08-19T16:31:58.747

1Nifle: Very nice answer. On my Vista box, I had to make two modifications: "can't do inplace edit without backup" was an error that I got. And, since the date necessarily uses the '/' char, I switched to use '#' as a delimiter. So here it is perl -pi.bak -e 's#@@@@#8/19/11#g' Edittable-failsafe.pga – Rolnik – 2011-08-19T16:39:02.700

2

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:\Path\To\File.txt; $foo | %{$_.replace('@@@@', '8/1/11')} | Out-File C:\Path\To\File.txt

EBGreen

Posted 2011-08-19T13:27:54.183

Reputation: 7 834

0

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

obaqueiro

Posted 2011-08-19T13:27:54.183

Reputation: 421