您没有认真研究第二个链接的答案 - 它有一个非常有效的解决方案。
我更喜欢这种技术的变体,它使用*]= 替换而不是子字符串:
@echo off
setlocal enableextensions disabledelayedexpansion
set "search=<Tool>"
set "replace=XYZ"
set "textFile=C:\abc.txt"
for /f "delims=" %%i in ('type "%textFile%" ^| find /v /n "" ^& break ^> "%textFile%"') do (
set "line=%%i"
setlocal enabledelayedexpansion
set "line=!line:*]=!"
if defined line set "line=!line:%search%=%replace%!"
>>"%textFile%" echo(!line!
endlocal
)
但是代码没有优化——附加重定向会减慢速度,因为必须打开输出文件,并且每次循环迭代都必须将文件指针定位到文件末尾。在循环之外重定向到一个临时文件,然后使用 MOVE 将原始文件替换为临时文件,速度要快得多。
我也更喜欢使用 FINDSTR 而不是 FIND - 它可以更好地处理长行,并且不需要管道或重定向。
@echo off
setlocal enableextensions disabledelayedexpansion
set "search=<Tool>"
set "replace=XYZ"
set "textFile=C:\abc.txt"
>"%textFile%.new" (
for /f "delims=" %%i in ('findstr /n "^" "%textFile%"') do (
set "line=%%i"
setlocal enabledelayedexpansion
set "line=!line:*:=!"
if defined line set "line=!line:%search%=%replace%!"
echo(!line!
endlocal
)
)
move /y "%textFile%.new" "%textFile%" >nul
说实话,我再也不使用纯批处理来修改文本文件了。有太多的边缘情况需要大量神秘的代码来解决。上面的代码还有很多潜在的问题。例如:
- 搜索字符串不能包含
=
- 搜索字符串不能以
* 或! 开头
- 替换字符串不能包含
!
- 如果搜索和/或替换同时包含
" 以及&、| 等有毒字符,则替换可能会失败。
我改用JREPL.BAT regular expression find/replace utility。它更快、更健壮、更强大。它是纯脚本(混合批处理/JScript),可以在从 XP 开始的任何 Windows 机器上本地运行,无需任何第三方 exe 文件。
例如,以下简单命令可以非常快速地查找/替换您的文字。
call jrepl "<Tool>" "XYZ" /l /f "C:\abc.txt" /o -