Shahgee
Shahgee

Reputation: 3405

Merge Two text files batch script

I need to have a batch file to combine two text files. My files are:

file1.txt
1
2
3
4

file2.txt
A
B
C
D
E
F
G
H
I
J
K
L

I need to get mixfile that looks like this

mix.txt
1
A
B
C
D
2
E
F
G
H
3
I
J
K
L

Note: for each line of file 1 I need 4 lines from file 2. 1->1-4,2->5-8, 3->9-12

I tried this program (bat file solution), but donot know, how to modify it to get the results with my requirements.

@echo off
set f1=file1.txt
set f2=file2.txt
set outfile=mix.txt
type nul>%outfile%
(
    for /f "delims=" %%a in (%f1%) do (
        setlocal enabledelayedexpansion
        set /p line=
        echo(%%a!line!>>%outfile%
        endlocal
    )
)<%f2%

pause

Upvotes: 0

Views: 297

Answers (1)

aschipfl
aschipfl

Reputation: 34989

You will need some kind of line counter:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Improved quoted `set` syntax:
set "f1=file1.txt"
set "f2=file2.txt"
set "outfile=mix.txt"
set "quotient=4"
rem // Redirect the whole block once:
< "%f1%" > "%outfile%" (
    rem // Temporarily precede each line with a line number:
    for /f "delims=" %%a in ('findstr /N "^" "%f2%"') do (
        rem // Get modulo of the line number:
        set "item=%%a" & set /A "num=(item+quotient-1)%%quotient"
        setlocal EnableDelayedExpansion
        rem // Return a line from the other file only if modulo is zero:
        if !num! equ 0 (
            set "line=" & set /P line=""
            echo(!line!
        )
        rem // Return current line with the line number prefix removed:
        echo(!item:*:=!
        endlocal
    )
)
endlocal
pause

The length of file2.txt determines how many iterations occur.

Upvotes: 1

Related Questions