【问题标题】:Replace a specific line in a batch file with the content of a text file?用文本文件的内容替换批处理文件中的特定行?
【发布时间】:2021-06-29 17:30:14
【问题描述】:

有没有办法可以使用 type 命令将批处理文件中的特定行替换为文本文件的内容?

例如,假设我有一个这样的批次:

@echo off
echo hello world
::replace
pause>nul
exit

我想将::replace 行替换为文本文件的内容,例如:

echo this
echo was
echo replaced

这可能吗?如果没有,还有其他方法可以做到这一点吗?

【问题讨论】:

    标签: batch-file text replace types


    【解决方案1】:

    如果该行与 ::replace 完全匹配,则此示例将替换该行,而不是包含。第一个示例替换了主脚本本身中的行:

    @echo off
    set "infile=%~0"
    for /f "delims=" %%i in ('type "%infile%" ^| find /v /n "" ^& break^>%infile%') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        set "line=!line:*]=!"
        if "!line!" == "::replace" (
           set line=
           type replace_file.txt
        )>>!infile!
        echo(!line!>>!infile!
        endlocal
     )
    
    rem sample replace section here.
    @echo off
    echo hello world
    ::replace
    pause>nul
    

    让它替换另一个批处理文件中的行,然后在显示“在此处添加文件名”的位置添加文件名:

    @echo off
    set "infile=ADD FILE NAME HERE"
    for /f "delims=" %%i in ('type "%infile%" ^| find /v /n "" ^& break^>%infile%') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        set "line=!line:*]=!"
        if "!line!" == "::replace" (
           set line=
           type replace_file.txt
        )>>!infile!
        echo(!line!>>!infile!
        endlocal
     )
    

    但请注意,这是用breaking 替换脚本本身并在替换您要求的内容时重新创建它。如果您犯了错误并破坏了代码,它将破坏您的脚本,因此请始终复制要替换代码的脚本。您可以通过在脚本中添加一行来自动执行此操作以复制之前的文件for 循环。比如:

    copy "%infile%" "%infile%.bck"
    

    【讨论】:

    • 哦,你知道,你的搜索/替换字符串不能包含任何感叹号!,如果你有一行,那么你不能使用延迟扩展。
    • 天哪,非常感谢它完美地工作!
    猜你喜欢
    • 2016-05-15
    • 2020-04-05
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    相关资源
    最近更新 更多