Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search and replace in a file using windows batch programming

Tags:

batch-file

I have a batch file that I want to open a file and do a very simple search and replace of that file and then save (overwrite) the file it did the search and replace on.

I know how to read the first line of a file:

set /p file= < file.txt

but struggling on the batch method of reading a whole file and doing search/replace on it.

like image 939
Christopher Padfield Avatar asked Oct 25 '25 08:10

Christopher Padfield


1 Answers

Replace the filename.txt and search1/replace1 with your filename and the proper search/replace strings or text.

 Echo off
    set "textfile=filename.txt"
    set "tempfile=filenametemp.txt"
    (for /f "delims=" %%i in (%textfile%) do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        set "line=!line:search1=replace1!"
        echo(!line!
        endlocal
    ))>"%tempfile%"
    del %textfile%
    rename %tempfile%  %textfile%
like image 167
Johan A. Avatar answered Oct 27 '25 05:10

Johan A.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!