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

后端 未结 1 1273
旧时难觅i
旧时难觅i 2020-11-29 02:44

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         


        
相关标签:
1条回答
  • 2020-11-29 03:43
    @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.

    0 讨论(0)
提交回复
热议问题