Replace a fixed value with a variable in a text file with batch

1.2k views Asked by At

I want to replace OLD with %NEW% in test.txt by using a batch file:

@echo off 
set /p NEW=""
set InputFile=test.txt
find OLD
replace %NEW%

my test.txt contains various characters like ~ : ; _ .which I attribute to various solutions clapping out.

I have attempted to use BatchSubstitude.bat to achieve this but it does not "find" OLD and does not replace any text.

I have also attempted to use fart.exe but I receieve an error when trying to perform this:

find_string="OLD"
replace_string="test"
actual find_length=3
actual replace_length=4
processing \filepath\,test.txt
skipping binary file: \filepath\test.txt

The documentation for this is sparse and nothing I could google furiously would provide a solution.

The reason I am using batch for the moment is that I perform various windows CE actions such as cecopy, pdel and rapistart for windows CE deployment over activesync and batch seems to be the easiest way to to get the result that I am after - and I'm a total noob at batch.

Does anyone know how this can be achieved with batch and perhaps explain how the various functions work to achieve this?

Cheers!

2

There are 2 answers

1
Aacini On BEST ANSWER

Try this:

@set @a=0  /*

@echo off 
set /p NEW=""
set InputFile=test.txt
cscript //nologo //E:JScript "%~F0" "%NEW%" < "%InputFile%" > output.tmp
move /Y output.tmp "%InputFile%"

@goto :EOF */

WScript.Stdout.Write(WScript.Stdin.ReadAll().replace(/OLD/g,WScript.Arguments(0)));
2
npocmaka On

Do not download anything from sourceforge so better to skip fart-it. The method in the dostips is not so robust when special characters are used (&<>|^) as it is pointed there.Here's a simple batch/jscript that will replace a content in a file (you can change the hardcoded things like file location):

0</* :
@echo off

set "file=c:\test.txt"
set "find=OLD"
set /p "replace=NEW: "
cscript /nologo /E:jscript "%~f0" %file% %find% %replace%

echo ==replaced==


exit /b */0;

var FSOObj = new ActiveXObject("Scripting.FileSystemObject");
var ARGS = WScript.Arguments;
if (ARGS.Length < 3 ) {
 WScript.Echo("Wrong arguments");
 WScript.Quit(1);
}
var filename=ARGS.Item(0);
var find=ARGS.Item(1);
var replace=ARGS.Item(2);

var readStream=FSOObj.OpenTextFile(filename, 1);

var content=readStream.ReadAll();
readStream.Close();

function replaceAll(find, replace, str) {
  return str.replace(new RegExp(find, 'g'), replace);
}

var newConten=replaceAll(find,replace,content);

var writeStream=FSOObj.OpenTextFile(filename, 2);
writeStream.WriteLine(newConten);
writeStream.Close();

Check also this more advanced tools

FindRepl

JRepl