merging two .txt files by alternating x lines from file 1 and y lines from file2

Hi everyone,

I have two files (A and B) and want to combine them to one by always taking 10 rows from file A and subsequently 6 lines from file B. This process shall be repeated 40 times (file A = 400 lines; file B = 240 lines).

Does anybody have an idea how to do that using perl, awk or sed?

Thank you so much in advance!
Iris

------------------------------------------------------------------------------
File A
------------------------------------------------------------------------------

0000 0    BIROB    18    brb    PSI    2    99
0001 17    ROBER    9    rbr    PSI    2    99
0002 5   TASOT    16    tst    PSI    2    99
0003 78    KASEK    6    ksk    PSI    2    99
...

-------------------------------------------------------------------------------
File B
-------------------------------------------------------------------------------

0000 N    NNNNN    N    N    CCCCC    NNN    2
0001 P    PPPPP    P    P    CCCCC    PPP    1
0002 P    PPPPP    P    P    CCCCC    PPP    1
0003 P    PPPPP    P    P    CCCCC    PPP    1
0004 N    NNNNN    N    N    CCCCC    NNN    2

Could this help you? (Code not tested)

#!/bin/sh
i=0
j=6
k=0
while read line1
do
    echo $line1
    i=$i+1
    if [ $i -eq 10 ]
    then
        awk -v start=$k -v end=$j  'NR > start && NR <= end' file2
        k=$j
        j=$j+6
        i=0
    fi
done < file1

Thanks!
Unfortunately, it doesn't read or print the lines from file2 so that it just takes all lines from file1 and prints those.

Any idea why it doesn't do the if loop?

Try this,

#!/bin/sh
i=0;j=6;k=0
while read line1
do
    echo $line1
    i=$(($i+1))
    if [ $i -eq 10 ]
    then
        awk -v start=$k -v end=$j  'NR > start && NR <= end' file2
        k=$j;j=$(($j+6));i=0
    fi
done < file1
1 Like

Thank you so much! It now works perfectly!

A Perl:

#!/usr/bin/perl
use strict;

my $fileA=shift;
my $fileB=shift;
my $fileR=shift;

open (FA,"<",$fileA ) || die "Can't open $fileA\n";
my @txtA=<FA>;
close(FA);

open (FB,"<",$fileB ) || die "Can't open $fileB\n";
my @txtB=<FB>;
close(FB);

open (FR,">",$fileR ) || die "Can't open $fileR\n";

my ($contA,$a,$contB,$b)=0;

for my $i ( 1 .. 40 ) {
   for $a ( 1 .. 10 ) {
      $a+=$contA;
      print FR $txtA[$a];
      }
   $contA+=10;
   for $b ( 1 .. 6 ) {
      $b+=$contB;
      print FR $txtB[$b];
      }
   $contB+=6;
   }    

close(FR);
    
exit;

Usage:

script.pl filea fileb result
1 Like

By shell script:

i=1;j=1;k=10;l=6
line=`cat file1 |wc -l`

while (true)
do
    m=`expr $i + $k - 1`
    n=`expr $j + $l - 1`
    sed -n "${i},${m}p" file1
    sed -n "${j},${n}p" file2
    i=`expr $i + $k`
    j=`expr $j + $l`
    if [ $i -gt $line ]; then
      exit
    fi
done

One-line awk (speed faster, because file1 and file2 are only read by one time.)

awk 'NR%10{print;next} {print;for (i=1;i<=6;i++) {getline < "file2";print} }' file1
1 Like