一个 batch 替换字符串脚本

暂时先存下来。

:REPLACE_STR
setLocal EnableDelayedExpansion
for /f "tokens=1,* delims=]" %%A in ('"type %3|find /n /v """') do (
    set "line=%%B"
    if defined line (
        set "line=!line:%~1=%~2!"
        echo.!line!
    ) else echo.
)
goto:eof

简单注释一下:

- EnableDelayedExpansion 用来使能 !! 操作符,使得变量可以在运行时赋值

- '"type %3|find /n /v """', 打印文件中的所有行,且在行首打印行号

- for /f "tokens=1,* delims=]" %%A in ,从上一句打印的内容中,匹配每一行行首的 ],记为字符串 A,后面部分顺序标记为字符串 B

- set "line=%%B", 将字符串B 赋值给变量 line;如果这一行为空,则 line 并不会被定义

-set "line=!line:%~1=%~2!",使用 !! 操作符,替换字符串中内容,这句只有使能 delayed Expansion 才能生效

-echo.!line!, 如果 line 为非空格字符,直接打印 line,否则打印一个换行

-echo. 直接打印一个换行

使用:

call :REPLACE_STR "old_str" "new_str" "input_file" > output_file

——————
无论在哪里做什么,只要坚持服务、创新、创造价值,其他的东西自然都会来的。
原文地址:https://www.cnblogs.com/pied/p/15667132.html