How can I merge files line by line in the Windows command line?

5,649

Solution 1

Nope, you'll need to merge the lines with a program, or a scripting language, like Python.

Update: Look at these Win ports of GNU utilities, it includes paste (.exe)

Solution 2

Definitely agree that a port of Unix tools or a scripting language is the way to go (although VBScript or Powershell are probably more convenient choices than Python for Windows users), but merging two files IS possible in DOS:-

@ECHO OFF

REM .bat to merge 1.txt and 2.txt

GOTO :Main

:StartMerge
    SET /P _a=<%1
    SET /P _b=<%2

    ECHO %_a% %_b%

    DEL %1 %2

    GOTO :EndMerge

:CleanUp
    SET _LinesIn1=
    SET _LinesIn2=

    SET _a=
    SET _b=

    GOTO :EOF

:Main
    SET _LinesIn1=0
    SET _LinesIn2=0

    FOR /F "delims=: tokens=1,*" %%i IN ('findstr /n "^" 1.txt') DO (
        ECHO.%%j>_c1n%%i
        SET /A _LinesIn1+=1
    )

    FOR /F "delims=: tokens=1,*" %%i IN ('findstr /n "^" 2.txt') DO (
        ECHO.%%j>_c2n%%i
        SET /A _LinesIn2+=1
    )

    IF %_LinesIn1% NEQ %_LinesIn2% (
        ECHO Cannot merge files; mismatched line count:-
        ECHO   1.txt - %_LinesIn1% lines
        ECHO   2.txt - %_LinesIn2% lines

        DEL _c*

        GOTO :CleanUp
    )

    FOR /L %%n IN (1, 1, %_LinesIn1%) DO (
        CALL :StartMerge _c1n%%n _c2n%%n

        :EndMerge
        REM No-op to avoid ") was unexpected at this time." error
    )

    GOTO :CleanUp

File under "Just because you can, doesn't mean you should." :-)

Solution 3

If the data reasonably simple, you could do it with Excel. Or you could download OpenOffice and do it in Calc, but the method in Calc is a pain. (You need to paste the data into two columns then merge them with the "Concatenate" function, in formula form (e.g. concatenate(Row1; row2;))

Share:
5,649

Related videos on Youtube

Paul
Author by

Paul

Updated on September 17, 2022

Comments

  • Paul
    Paul over 1 year

    In dos, is there a way to merge a set of files so that for instance

    1.txt

    a
    b
    c

    and

    2.txt

    1
    2
    3

    becomes

    merged.txt

    a 1
    b 2
    c 3

    Just like the paste command on *nix systems

    • akira
      akira almost 14 years
      dos as in "dos - operating system" or as in "windows cmd.exe" ?
    • XIMRX
      XIMRX over 9 years
      cygwin works for me
  • Paul
    Paul almost 14 years
    Too bad. Sukcs not to have Linux at work... :p
  • akira
    akira almost 14 years
    @Paul: install cygwin.com/setup.exe