用于将两个文件中的行合并到第三个文件的批处理脚本

时间:2011-11-16 14:01:18

标签: file batch-file merge

档案A1的内容:

AA
VV
BB

档案A2的内容:

DD
EE
FF

我想将A1A2的内容合并到A3,以便A3中的预期数据为:

AADD
VVEE
BBFF

或者,A3中的预期输出可能是:

AA is from DD
VV is from EE
BB is from FF

感谢您的帮助。在我发布之前我确实尝试过搜索,找不到已经发布类似内容的人......

3 个答案:

答案 0 :(得分:3)

我们可以将文件的内容加载到Batch变量数组中,这样就可以以任何方式直接访问它的每一行:

@echo off
setlocal EnableDelayedExpansion

rem Load first file into A1 array:
set i=0
for /F "delims=" %%a in (A1.txt) do (
    set /A i+=1
    set A1[!i!]=%%a
)

rem Load second file into A2 array:
set i=0
for /F "delims=" %%a in (A2.txt) do (
    set /A i+=1
    set A2[!i!]=%%a
)

rem At this point, the number of lines is in %i% variable

rem Merge data from both files and create the third one:
for /L %%i in (1,1,%i%) do echo !A1[%%i]! is from !A2[%%i]!>> A3.txt

编辑 替代解决方案

还有另一种方法可以不使用批处理变量,因此它可以用于任何大小的文件,尽管速度较慢。我借用了Andy Morris在其解决方案中使用的方法:1-在两个文件中插入行号,2-将两个文件合并为一个,3-对组合文件进行排序,4-将行组合并到同一行。下面的程序基本上是Andy的一个,它有几个小的修改,使它更快(修复了一个微妙的错误)。

@echo off
setlocal EnableDelayedExpansion

call :AddLineNumbers A1.txt A > Both.txt
call :AddLineNumbers A2.txt B >> Both.txt
sort Both.txt /O Sorted.txt
echo EOF: >> Sorted.txt
call :creatNewLines < Sorted.txt > Result.txt
goto :eof

:AddLineNumbers
findstr /n ^^ %1 > tem.tmp
for /f "tokens=1* delims=:" %%a in (tem.tmp) do (
    set /a lineNo=1000000+%%a
    echo !lineNo!%2:%%b
)
goto :eof

:creatNewLines
set /p lineA1=
for /f "tokens=1* delims=:" %%a in ("%lineA1%") do (
    if %%a == EOF goto :eof
    set /p dummy=%%b< nul
)
set /p lineA2=
for /f "tokens=1* delims=:" %%a in ("%lineA2%") do echo  is from %%b
goto creatNewLines

SORT命令基于其内容的命令行。 Andy的原始方法可能会失败,因为在行号之后行根据行内容排序,因此每个文件的行可能放错了位置。在此方法中,在行号后面添加了一个附加字符(A或B),因此每个文件的行总是放在正确的位置。

答案 1 :(得分:1)

如果您的原始数据位于Data1.txt和Data2.txt中,则应执行以下操作:

@echo off

    call :AddLineNumbers data1.txt Tem1.txt
    call :AddLineNumbers data2.txt Tem2.txt

    copy tem1.txt + tem2.txt tem3.txt 
    sort < tem3.txt > tem4.txt

    call :GetDataOut tem4.txt > tem5.txt

    set OddData=

    for /f %%a in (tem5.txt) do call :creatNewLines %%a

goto :eof



:AddLineNumbers

    find /v /n "xx!!xx" < %1 > tem.txt


    call :ProcessLines > %2


goto :eof

:ProcessLines

    for /f  "tokens=1,2 delims=[]"  %%a in (tem.txt) do call :EachLine %%a %%b 

goto :eof

:eachLine

    set LineNo=00000%1
    set data=%2 

    set LineNo=%LineNo:~-6%

    echo %LineNo% %data% 

goto :eof

:GetDataOut 
    for /f "tokens=2" %%a in (%1) do @echo %%a
goto :eof

:creatNewLines
    if "%oddData%"=="" (
        set oddData=%1
    ) else (
        echo %oddData% %1
        set oddData=
    )
goto :eof

答案 2 :(得分:0)

如果使用linux,我建议使用剪切和粘贴(命令行)。参见手册页。

或者,如果您不需要自动化,则可以使用vim块模式剪切和粘贴。使用control-v。

进入块模式可视模式