Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace substrings in windows batch file

Tags:

batch-file

Can anyone tell me using batch file in windows ...how to read from a file and replace string=bath from file containing=bath Abath Bbath XYZbathABC with string hello so that the output is like hello Ahello Bhello XYZhelloABC

like image 933
Enosh Bansode Avatar asked Mar 11 '11 14:03

Enosh Bansode


People also ask

How can you find and replace text in a file using the Windows command line?

(gc myFile. txt) reads the content of myFile. txt ( gc is short for the Get-Content command) -replace 'foo', 'bar' simply runs the replace command to replace foo with bar.

What does %1 mean in a batch file?

When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.


1 Answers

Expanding from Andriy M, and yes you can do this from a file, even one with multiple lines

@echo off setlocal EnableExtensions EnableDelayedExpansion set "INTEXTFILE=test.txt" set "OUTTEXTFILE=test_out.txt" set "SEARCHTEXT=bath" set "REPLACETEXT=hello"  for /f "delims=" %%A in ('type "%INTEXTFILE%"') do (     set "string=%%A"     set "modified=!string:%SEARCHTEXT%=%REPLACETEXT%!"     echo !modified!>>"%OUTTEXTFILE%" )  del "%INTEXTFILE%" rename "%OUTTEXTFILE%" "%INTEXTFILE%" endlocal 

EDIT

Thanks David Nelson, I have updated the script so it doesn't have the hard coded values anymore.

like image 142
aflat Avatar answered Oct 12 '22 04:10

aflat