简体   繁体   English

使用批处理脚本在文本文件中查找和替换字符串的算法,有效,但随机停止

[英]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.我在 Stack Overflow 上找到了另一个用户提供的这个解决方案,它完成了这项工作,但是,它只是在某个随机点停止迭代文本文件,反过来,output 文件留下了一堆未从原始文件。 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提供的代码,感谢Ryan Bemrose在这个问题

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:以下将稳健地处理所有 Ascii 可打印字符*1 ,并保留源文件中存在的空行:

@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: *1注意 - 由于 substring 修改的操作方式,您无法替换以下搜索字符串:

  • contain the = Operator包含=运算符
  • Begin with ~开始~

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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