in reply to Splitting big file or merging specific files?
Hello zarath,
Something like that could work.
I am sure that another Monk will come up with a better solution but is a good working starting point.
#!usr/bin/perl use say; use strict; use warnings; open(my $fh1, ">>", "output1.txt") or die "Can't open > output1.txt: $!"; open(my $fh2, ">>", "output2.txt") or die "Can't open > output2.txt: $!"; my $count = 1; while (<>) { # Read all files that provided through ARGV chomp; if ($count == 1 or $count == 2) { say $fh1 $_; } elsif ($count == 3 or $count == 4) { say $fh2 $_; } if ($count == 4) { $count = 1; } else { $count++; } } continue { close ARGV if eof; # reset $. each file } close($fh1) or warn "Can't close output1.txt: $!"; close($fh2) or warn "Can't close output2.txt: $!"; __END__ $ cat output1.txt Sample of text line 1 Sample of text line 2 Sample of text line 5 Sample of text line 6 $ cat output2.txt Sample of text line 3 Sample of text line 4
The code is self explained, you provide the script $ perl test.pl in.txt and then the output files are defined inside. I open them in append mode so every line that we print is bellow the other.
Update: Minor code modification:
#!usr/bin/perl use say; use strict; use warnings; open(my $fh1, ">>", "output1.txt") or die "Can't open > output1.txt: $!"; open(my $fh2, ">>", "output2.txt") or die "Can't open > output2.txt: $!"; my $count = 1; while (<>) { # Read all files that provided through ARGV chomp; if ($count == 1 or $count == 2) { say $fh1 $_; } elsif ($count == 3 or $count == 4) { say $fh2 $_; } if ($count == 4) { $count = 1; next; } $count++; } continue { close ARGV if eof; # reset $. each file } close($fh1) or warn "Can't close output1.txt: $!"; close($fh2) or warn "Can't close output2.txt: $!";
Update2: Minor code improvement:
#!usr/bin/perl use say; use strict; use warnings; open(my $fh1, ">>", "output1.txt") or die "Can't open > output1.txt: $!"; open(my $fh2, ">>", "output2.txt") or die "Can't open > output2.txt: $!"; while (<>) { # Read all files that provided through ARGV chomp; if ($. == 1 or $. == 2) { say $fh1 $_; } elsif ($. == 3 or $. == 4) { say $fh2 $_; } $. = 0 if ($. == 4); } continue { close ARGV if eof; # reset $. each file } close($fh1) or warn "Can't close output1.txt: $!"; close($fh2) or warn "Can't close output2.txt: $!";
Final Update:
Just for fun removing unnecessary elsif:#!usr/bin/perl use say; use strict; use warnings; open(my $fh1, ">>", "output1.txt") or die "Can't open > output1.txt: $!"; open(my $fh2, ">>", "output2.txt") or die "Can't open > output2.txt: $!"; while (<>) { # Read all files that provided through ARGV chomp; if ($. == 1 or $. == 2) { say $fh1 $_; next; } say $fh2 $_; $. = 0 if ($. == 4); } continue { close ARGV if eof; # reset $. each file } close($fh1) or warn "Can't close output1.txt: $!"; close($fh2) or warn "Can't close output2.txt: $!";
Hope this helps, BR.
|
|---|