0

I have a batch adapted from @MC ND, that search for a string and replace it in a given file.

It works well except that it deletes blank lines in my initial file.

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

The input file is :

A

To_be_replaced

B

I expect the output to be:

A

Well_Replaced

B

The actual output is:

A
Well_Replaced
B

How can I manage to not delete blank lines ?

R.Omar
  • 141
  • 1
  • 2
  • 11
  • 1
    [`for /F`](https://ss64.com/nt/for_f.html) removes blank lines; however, the [thread](https://stackoverflow.com/q/31314203) linked by user BDM demonstrates how to avoid that; an alternative to [`find /N /V ""`](https://ss64.com/nt/find.html) is [`findstr /N "^"`](https://ss64.com/nt/findstr.html) (but you'd need to change `delims` option then accordingly)... – aschipfl Apr 24 '19 at 10:57

1 Answers1

1

Here's an example based on the comments thus far:

@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)
Compo
  • 36,585
  • 5
  • 27
  • 39
  • It works perfectly good.. can you explain to me what it does in each part please ? – R.Omar Apr 24 '19 at 12:27
  • No I cannot! You can instead open a Command Prompt window, enter each of the commands used, appended with its help switch `/?`, read the content and try to learn and understand it yourself. Together with the information in the linked 'duplicate', it shouldn't be an impossibility to work it out yourself. – Compo Apr 24 '19 at 12:33