Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

Tags:

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..

like image 217
ananth joshi Avatar asked Apr 15 '14 06:04

ananth joshi


People also ask

What is %~ dp0 in batch script?

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:\.

How do you create a batch file from a text file?

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.


1 Answers

@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.

like image 199
MC ND Avatar answered Sep 23 '22 03:09

MC ND