What would be the code in ksh/perl to read 2 files alternatively, based on the following condition.
while reading file 1 we check if a blank line is encountered,
if yes, then we read file 2 unless a blank line is encountered in file 2
if we have a blank line in file 2 we come back to file 1 and continue reading file 1 unless a blank line is encountered, and then continue to file 2, till reading both the files have complete.
The script give the output to console. if you want to save the output as a file, use the write file handler at end of the program or redirect the output to a file.
cmd# perl scriptname.pl > your_output_file_name
or
open (FOUT, ">output.txt") || die "Cannot create the output file";
for (my $i = 0; $i<=$#file1; $i++) {
print FOUT "\n----- Group ", $i+1," ------\n", "$file1[$i]\n", "$file2[$i]\n";
}
close (FOUT);
I just show the piece of code how to write the output to a file. I expect you collate code in the existing example. OK, tried the below code.
#!/usr/bin/perl
use strict;
use warnings;
my $file1=open_file("file1.txt");
my $file2=open_file("file2.txt");
my @file1 = split(/\n{2,}/, $file1);
my @file2 = split(/\n{2,}/, $file2);
open (FOUT, ">output.txt") || die "Cannot create the output file";
for (my $i = 0; $i<=$#file1; $i++) {
print FOUT "\n----- Group ", $i+1," ------\n", "$file1[$i]\n", "$file2[$i]\n";
}
close (FOUT);
sub open_file
{
my ($fname)=@_;
undef $/;
open (FIN, "<", "$fname") || die "Cannot open the input file $fname : $!";
my $fcontent=<FIN>;
close (FIN);
return "$fcontent\n";
}