批量替换字符串但同时删除空行
Batch replaces string BUT also deletes blank lines
我有一个改编自@MC ND 的批处理,用于搜索字符串并在给定文件中替换它。
除了删除我初始文件中的空行外,它运行良好。
@echo off
setlocal enableextensions disabledelayedexpansion
set "search=To_be_replaced"
set "replace=Well_Replaced"
set "File=TEST.txt"
for /f "delims=" %%i in ('type "%File%" ^& break ^> "%File%" ') do (
set "line=%%i"
setlocal enabledelayedexpansion
>>"%File%" echo(!line:%search%=%replace%!
endlocal
)
输入文件是:
A
To_be_replaced
B
我希望输出为:
A
Well_Replaced
B
实际输出为:
A
Well_Replaced
B
如何才能不删除空行?
这是一个基于目前评论的示例:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "search=To_be_replaced"
Set "replace=Well_Replaced"
Set "File=TEST.txt"
For /F "Tokens=1*Delims=]" %%A In ('Find /V /N ""^<"%File%"^&Break^>"%File%"'
)Do (Set "line=%%B"
SetLocal EnableDelayedExpansion
(If Not "%%B"=="" (Echo(!line:%search%=%replace%!)Else Echo()>>"%File%"
EndLocal)
我有一个改编自@MC ND 的批处理,用于搜索字符串并在给定文件中替换它。
除了删除我初始文件中的空行外,它运行良好。
@echo off
setlocal enableextensions disabledelayedexpansion
set "search=To_be_replaced"
set "replace=Well_Replaced"
set "File=TEST.txt"
for /f "delims=" %%i in ('type "%File%" ^& break ^> "%File%" ') do (
set "line=%%i"
setlocal enabledelayedexpansion
>>"%File%" echo(!line:%search%=%replace%!
endlocal
)
输入文件是:
A
To_be_replaced
B
我希望输出为:
A
Well_Replaced
B
实际输出为:
A
Well_Replaced
B
如何才能不删除空行?
这是一个基于目前评论的示例:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "search=To_be_replaced"
Set "replace=Well_Replaced"
Set "File=TEST.txt"
For /F "Tokens=1*Delims=]" %%A In ('Find /V /N ""^<"%File%"^&Break^>"%File%"'
)Do (Set "line=%%B"
SetLocal EnableDelayedExpansion
(If Not "%%B"=="" (Echo(!line:%search%=%replace%!)Else Echo()>>"%File%"
EndLocal)