@echo off
::old string and replace string
set old_str=ip
set new_str=#ip
:FILE
set "souerce_path=D:\xxx\bat\my_test.txt"
for /f "tokens=1* delims=:" %%i in ('findstr /n .* "%souerce_path%"') do (
set "lineContent=%%j"
::echo ==%%j==
setlocal EnableDelayedExpansion
if not "!lineContent!"=="" set "lineContent=!lineContent:%old_str%=%new_str%!"
>>"temp.txt" echo.!lineContent!
endlocal
)
move /y temp.txt "%souerce_path%"
goto END
:PATH
::files path
set "souerce_path=D:/xxx/bat"
cd /d "%souerce_path%"
:: dir /s /b /a-d *.txt ::get all current and sub path file name with post .txt
for /f "delims=" %%a in ('dir /s /b /a-d *.txt') do (
for /f "tokens=1* delims=:" %%i in ('findstr /n .* "%%a"') do (
set "lineContent=%%j"
::echo ==%%j==
::here use "setlocal EnableDelayedExpansion" to keep content "!"
setlocal EnableDelayedExpansion
if not "!lineContent!"=="" set "lineContent=!lineContent:%old_str%=%new_str%!"
>>"%%~dpnxas" echo.!lineContent!
endlocal
)
del /s /q /f "%%a" >nul
ren *.txts *.txt
)
:END
批处理BAT:文件中替换字符并保留空行、空格、换行亲测可用
于 2024-04-11 21:57:09 首次发布