批量替换字符串但也删除空白行

时间:2019-04-24 10:45:02

标签: batch-file replace blank-line

我有一个来自@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

我如何不删除空白行?

1 个答案:

答案 0 :(得分:1)

这是迄今为止的评论示例:

@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)