Batch file 使用批处理脚本查找和替换

Batch file 使用批处理脚本查找和替换,batch-file,Batch File,我一直在为下面的任务编写批处理脚本。 假设我有以下文本文件 A.txt B.txt 我的output.txt文件应该包含 hello world-0 hi CAT hello world-1 hi MAT hello world-2 hi RAT 如何使用批处理脚本实现这一点? 谢谢 试试这个 @echo off setlocal enableextensions enabledelayedexpansion rem Read a.txt with findstr /n to avoid

我一直在为下面的任务编写批处理脚本。 假设我有以下文本文件

A.txt

B.txt

我的output.txt文件应该包含

hello world-0
hi CAT

hello world-1
hi MAT

hello world-2
hi RAT
如何使用批处理脚本实现这一点? 谢谢

试试这个

@echo off
setlocal enableextensions enabledelayedexpansion

rem Read a.txt with findstr /n to avoid blank line removal
rem Read b.txt with set /p only when a replacement is needed

< "b.txt" (
    for /f "tokens=1,* delims=:" %%f in ('findstr /n "^" ^<"a.txt"') do (
        set "line=%%g"
        if defined line if not "!line: ABC=!"=="!line!" (
            set /p "repl="
            for /f %%r in ("!repl!") do set "line=!line: ABC= %%r!"
        )
        echo(!line!
    )
)

endlocal

这应该可以完成这项工作。

使用好的文件解析工具,如awk。你可以下载awk

hello world-0
hi CAT

hello world-1
hi MAT

hello world-2
hi RAT
@echo off
setlocal enableextensions enabledelayedexpansion

rem Read a.txt with findstr /n to avoid blank line removal
rem Read b.txt with set /p only when a replacement is needed

< "b.txt" (
    for /f "tokens=1,* delims=:" %%f in ('findstr /n "^" ^<"a.txt"') do (
        set "line=%%g"
        if defined line if not "!line: ABC=!"=="!line!" (
            set /p "repl="
            for /f %%r in ("!repl!") do set "line=!line: ABC= %%r!"
        )
        echo(!line!
    )
)

endlocal
C:\>awk "FNR==NR{a[++c]=$1;next}{ for(i=1;i<=NF;i++){ if($i==\"ABC\") { $i=a[++d] } }  }1" B.txt A.txt
hello world-0
hi CAT

hello world-1
hi MAT

hello world-2
hi RAT