SoFunction
Updated on 2025-04-08

Batch Keep empty lines to replace strings


@echo off
:: Keep empty lines to replace string
:: When there is a colon at the beginning of the line, the first few consecutive colons will be thrown away (this problem can be solved)
:: will ignore lines starting with a semicolon
:: Cannot handle exclamation marks correctly (because variable delay is enabled)
::
::

set file=
set /p file= Please pull the file to be processed to this window:
set "file=%file:"=%"
for %%i in ("%file%") do set "file=%%~fi"
echo.
set replaced=
set /p replaced= Please enter the content to be replaced:
echo.
set all=
set /p all= Please enter the replacement string:
cd.>"%file%_tmp.txt"
setlocal enabledelayedexpansion
for /f "tokens=1* delims=:" %%i in ('findstr /n .* "%file%"') do (
set str=%%j
if not "!str!"=="" set "str=!str:%replaced%=%all%!"
>>"%file%_tmp.txt" echo.!str!
)
copy "%file%" "%file%_bak.txt" >nul 2>nul
move "%file%_tmp.txt" "%file%"
start "" "%file%"