1

I would like to make a zigzag merging of two text files as following. I have two files in input:

file1.txt
A
A
A

and

file2.txt
B
B
B

I would like to have as output:

output.txt
A
B
A
B
A
B

Can anyone please tell me which may be the simpliest way to do this in batch (I'm forced to use this native windows langage). Thank you!

MichaelS
  • 5,941
  • 6
  • 31
  • 46
Elhendriks
  • 119
  • 3
  • 14

2 Answers2

1

If we can assume that the number of lines in both files is equal, this will work:

@ECHO OFF
TYPE NUL>output.txt
SETLOCAL ENABLEDELAYEDEXPANSION
SET linecount=0

FOR /F %%i IN (file1.txt) DO SET /a linecount=!linecount!+1

FOR /L %%n IN (1,1,!linecount!) DO (
    FOR /f "tokens=1* delims=:" %%a in ('findstr /n .* "file1.txt"') DO (
        IF "%%a"=="%%n" SET lineA=%%b
    )
    FOR /f "tokens=1* delims=:" %%a in ('findstr /n .* "file2.txt"') DO (
        IF "%%a"=="%%n" SET lineB=%%b
    )
    ECHO !lineA! >> output.txt
    ECHO !lineB! >> output.txt
)

The first FOR loop simply count the lines in file1.txt. The second loop iterates over the number of lines. Both internal loops execute the command findstr /n .* "fileX.txt" on file1.txt and file2.txt. The /n parameter outputs the content of the file adding : at the beginning of each line. So we split each modified line with delimeter : and store everything after : if the line starts with the current line index which is incremented after each interation. So after n-th iteration of the "big" loop !lineA! contains contains the n-th line of the first file and !lineB! contains the n-th line of the second file and both lines are appended to output.txt.

MichaelS
  • 5,941
  • 6
  • 31
  • 46
0

Your process is called file merge and the simplest way to achieve it is reading the second file via redirected input. This method even works with more than two input files, as described at this post or this one.

@echo off
setlocal EnableDelayedExpansion

rem Second file will be read from redirected input
< fileB.txt (

   rem First file will be read via FOR /F
   for /F "delims=" %%a in (fileA.txt) do (
      echo %%a
      rem Read and write next line from second file
      set /P lineB=
      echo !lineB!
   )

rem Send result to output file
) > output.txt
Community
  • 1
  • 1
Aacini
  • 65,180
  • 12
  • 72
  • 108
  • You're welcome! Just a detail: check _the time_ that these solutions take to produce the result, specially if the input files are large... – Aacini Jun 29 '15 at 14:21