Batch - Zigzag merging with two files

隐身守侯 提交于 2021-01-28 12:00:32

问题


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!


回答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.




回答2:


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


来源:https://stackoverflow.com/questions/31071601/batch-zigzag-merging-with-two-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!