[英]Find and replace algorithm for string in text file using batch script, works, but stopping at random Line
作為序言:這是我的第一個批處理腳本
我一直在試圖弄清楚如何使用批處理腳本替換包含某個字符串的文本文件中的整行。 我在 Stack Overflow 上找到了另一個用戶提供的這個解決方案,它完成了這項工作,但是,它只是在某個隨機點停止迭代文本文件,反過來,output 文件留下了一堆未從原始文件。 我逐個字符,逐行查看腳本以弄清楚每個部分的確切作用,但似乎無法發現導致此錯誤的原因。
提供的代碼,感謝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
它停止的行總是包含<
或>
或兩者都包含|
會導致它停止,或者有時它會刪除該行並繼續。
您的幫助將不勝感激。
為了穩健地做到這一點,延遲擴展是必要的,以防止“毒”字符,如<
>
&
|
等被解釋為命令令牌。
但是請注意,在定義包含行值的變量以保留任何!
之前,不應啟用延遲擴展。 可能出現的字符。
以下將穩健地處理所有 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
注意 - 由於 substring 修改的操作方式,您無法替換以下搜索字符串:
=
運算符~
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.