Replace string in a file using batch scripting

May 1, 2019 at 01:43:33
Specs: DOS
I want to replace string in a file. Trying to implement below logic using For loop to replace a string across a big file. But it is not working. Please guide is the right way.

set str=This message needs changed.
echo %str%

set str=%str:needs=has%
echo %str%

Thanks!


See More: Replace string in a file using batch scripting

Reply ↓  Report •

#1
May 1, 2019 at 08:39:22
can i expect "%str%" somewhere randomly in the middle of a bigger sentence or should i expect %str% on a seperate line everytime?

The lather would be waaaaaay easier in batch at least (powershell might be able to do so in 1 line...)

i5-6600K[delid]@4.9GHz/4.4GHz cache@1.504v | 2x4GB Crucial-DDR4-2400CL17@CL12-15-15-28 1T 3000MHz@1.45v | Sapphire Nitro+ SE RX 590 8GB@1525Mhz core@1.0v/2250MHz@1500MHz timings BiosModded


Reply ↓  Report •

#2
May 2, 2019 at 01:05:22
input.txt:

123

2k32 h232h
This message needs changed.

sddljbbqfbq ljqwdljwqhq
fdfdd


fde


output.txt:


123

2k32 h232h
This message has changed.

sddljbbqfbq ljqwdljwqhq
fdfdd


fde

test.bat:

@echo off&setlocal enabledelayedexpansion
set "inputfile=input.txt"
set "outputfile=output.txt"
set "from=needs"
set "to=has"
:overwritefile
for /f "tokens=1,2* delims=[]" %%a in ('find /V /N "" "%inputfile%"') do (
	set "temp1=%%b"
	call :echotofile "!inputfile!"
)
exit/b
:echotofile
if "!temp1!"=="" (echo.>>"%outputfile%") else (if /I "!temp1:~-4!"=="!inputfile:~-4!" exit/b)
set "temp1=!temp1:%from%=%to%!"
if not "!temp1!"=="needs=has" echo.!temp1!>>"%outputfile%"
exit/b

edit: looks like it does add 1 extra empty line at the beginning of output.txt, hope that's not a big deal

i5-6600K[delid]@4.9GHz/4.4GHz cache@1.504v | 2x4GB Crucial-DDR4-2400CL17@CL12-15-15-28 1T 3000MHz@1.45v | Sapphire Nitro+ SE RX 590 8GB@1525Mhz core@1.0v/2250MHz@1500MHz timings BiosModded

message edited by hidde663


Reply ↓  Report •

#3
May 4, 2019 at 16:36:44
you can use the rem line ' ' to remove blank lines

Reply ↓  Report •

Related Solutions

#4
May 5, 2019 at 05:11:57
RE #3 i tried my very best to keep them in

i5-6600K[delid]@4.9GHz/4.4GHz cache@1.504v | 2x4GB Crucial-DDR4-2400CL17@CL12-15-15-28 1T 3000MHz@1.45v | Sapphire Nitro+ SE RX 590 8GB@1525Mhz core@1.0v/2250MHz@1500MHz timings BiosModded


Reply ↓  Report •

Ask Question