Click here for important information about Computing.net.

Solved Batch Script To Find And Replace A String In Text File

January 20, 2021 at 22:02:45
Specs: Windows 10
i have text file that contains more data in that i want to replace some data

the text file contains huge data and i want to search for a single word in the document and replace only the that word.
text file name is test.txt
the given sentence in the text file is :
the following are the series types

i want to change as:
the following are the axis types

it has to find the word " series" and replace as "axis" using batch script


See More: Batch Script To Find And Replace A String In Text File


#1
January 21, 2021 at 00:10:29
This batch with powershell can did easily the trick, just give a try :

@echo off
Title Search and Replace with Powershell and batch
set "String2Find=series"
set "ReplaceWith=axis"
Set "InputFile=%~dp0Test.txt"
Set "OutPutFile=%~dp0New_Test.txt"
Call :Search_Replace "%String2Find%" "%ReplaceWith%" "%InputFile%" "%OutPutFile%"
If Exist "%OutPutFile%" Start "" "%OutPutFile%"
Exit
REM -------------------------------------------------------------------
:Search_Replace <String2Find> <ReplaceWith> <InputFile> <OutPutFile>
Powershell ^
GC "%~3" ^| %% { $_ -Replace '"%~1"','"%~2"' } ^| Out-File "%~4"
Exit /B
REM -------------------------------------------------------------------

message edited by Hackoo


Reply ↓  Report •

#2
January 21, 2021 at 00:22:25
it has to run in command promt and the text has to be replaced in the same text documnet

message edited by sign


Reply ↓  Report •

#3
January 21, 2021 at 02:56:47
✔ Best Answer
You can save this file as Search_Replace.bat and call it from command prompt :

@echo off
Title Search and Replace
Set "Tmpvbs=%temp%\Tmpvbs.vbs"
set "String2Find=series"
set "ReplaceWith=axis"
Set "InputFile=%~dp0Test.txt"
@for %%f in ("%InputFile%") do Set "OutPutFile=%%~dpf%%~nf_New%%~xf"
Call :Replace %String2Find% %ReplaceWith% "%InputFile%" "%OutPutFile%"
If Exist "%Tmpvbs%" Del "%Tmpvbs%"
pause & exit
::*************************************************************
:Replace <String2Find> <ReplaceWith> <InputFile> <OutPutFile>
Cls & echo(
echo Searching "%~1" into file "%~3" to Replace with "%~2"
(
	echo Data = WScript.StdIn.ReadAll
	echo Data = Replace(Data,"%~1","%~2",1, -1, 1^)
	echo WScript.StdOut.WriteLine Data
)>"%Tmpvbs%"
cscript //nologo "%Tmpvbs%" < "%~3" > "%~4"
Move /Y "%~4" "%~3">nul
Timeout /T 1 /nobreak>nul
exit /b
::*************************************************************


Reply ↓  Report •

Related Solutions

#4
January 21, 2021 at 03:38:37
Can you explain the above code ..pls

Reply ↓  Report •

#5
January 21, 2021 at 11:51:44
@sign
Is you the same poster here ?? ==> https://www.computing.net/answers/w...

Reply ↓  Report •

Ask Question