I have written a batch script to find and replace a string in a text file. Following is my script.
@echo off &setlocal set "search=%1" set "replace=%2" set "textfile=Input.txt" set "newfile=Output.txt" (for /f "delims=" %%i in (%textfile%) do ( set "line=%%i" setlocal enabledelayedexpansion set "line=!line:%search%=%replace%!" echo(!line! endlocal ))>"%newfile%" del %textfile% rename %newfile% %textfile%
I am able to replace the word successfully.
But i dont want to create Output.txt and then rename it the original file..
Please help me out for editing a text file without redirecting the output to a new file..
For %~dp0, the current directory is the directory where the bat file resides. So if you put the batch file in c:\dir\test. bat and the file contains @echo %CD%, if you are now in C:\dir and execute test. bat, it will output c:\dir; if you are in c:\ and execute c:\dir\test. bat, it will output c:\.
To create a Windows batch file, follow these steps: Open a text file, such as a Notepad or WordPad document. Add your commands, starting with @echo [off], followed by, each in a new line, title [title of your batch script], echo [first line], and pause. Save your file with the file extension BAT, for example, test.
@echo off setlocal enableextensions disabledelayedexpansion set "search=%1" set "replace=%2" set "textFile=Input.txt" for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do ( set "line=%%i" setlocal enabledelayedexpansion >>"%textFile%" echo(!line:%search%=%replace%! endlocal )
for /f
will read all the data (generated by the type
comamnd) before starting to process it. In the subprocess started to execute the type
, we include a redirection overwritting the file (so it is emptied). Once the do
clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With