简体   繁体   中英

Find and replace algorithm for string in text file using batch script, works, but stopping at random Line

To preface this: This is my very first Batch script

I've been trying to figure out how to replace an entire line in a text file that contains a certain string using a Batch Script. I've found this solution provided by another user on Stack Overflow, which does the job, however, it just stops iterating through the text file at some random point and in turn, the output file is left with a bunch of lines untransferred from the original file. I've looked character by character, and line by line of the script to figure out what each part exactly does, and can not seem to spot what is causing this bug.

The code provided, thanks to Ryan Bemrose on this question

copy nul output.txt
for /f "tokens=1* delims=:" %%a in ('findstr /n "^" file.txt') do call :do_line "%%b"
goto :eof

:do_line
set line=%1
if {%line:String =%}=={%line%} (
  echo.%~1 >> output.txt
  goto :eof
)
echo string >> output.txt

The lines it is stopping at always either contain < or > or both and lines with | will either cause it to stop, or sometimes it will delete the line and continue.

Your help would be much appreciated.

To do this robustly, Delayed expansion is necessary to prevent "poison" characters such as < > & | etc being interpreted as command tokens.

Note however that delayed expansion should not be enabled until after the variable containing the line value is defined so as to preserve any ! characters that may be present.

The following will robustly handle all Ascii printable characters *1 , and preserve empty lines present in the source file:

@Echo off

Set "InFile=%~dp0input.txt"
Set "OutFile=%~dp0output.txt"
Set "Search=String "
Set "Replace="

>"%OutFile%" (
 for /F "delims=" %%G in ('%SystemRoot%\System32\findstr.exe /N "^" "%InFile%"') do (
  Set "line=%%G"
  call :SearchReplace
 )
)
Type "%OutFile%" | More
goto :eof

:SearchReplace
Setlocal EnableDelayedExpansion
 Set "Line=!Line:*:=!"
 If not defined Line (
  (Echo()
  Endlocal & goto :eof
 )
 (Echo(!Line:%Search%=%Replace%!)
Endlocal & goto :eof

*1 Note - Due to how substring modification operates, You cannot replace Search strings that:

  • contain the = Operator
  • Begin with ~

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM