-
Notifications
You must be signed in to change notification settings - Fork 33
/
split_to_n_lines.pl
executable file
·72 lines (56 loc) · 1.48 KB
/
split_to_n_lines.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/usr/bin/perl
# Author: Daniel "Trizen" Șuteu
# License: GPLv3
# Website: https://github.com/trizen
# Split a text file into sub files of 'n' lines each other
use strict;
use warnings;
use Getopt::Std qw(getopts);
use File::Spec::Functions qw(catfile);
my %opts;
getopts('l:', \%opts);
my $lines_n = $opts{l} ? int($opts{l}) : 100;
if (not @ARGV) {
die "Usage: $0 -l [i] <files>\n";
}
sub print_to_file {
my ($array_ref, $foldername, $num) = @_;
open(my $out_fh, '>', catfile($foldername, "$num.txt")) or return;
print $out_fh @{$array_ref};
close $out_fh;
return 1;
}
foreach my $filename (@ARGV) {
-f $filename or do {
warn "$0: skipping '$filename': is not a file\n";
next;
};
my $foldername = $filename;
if (not $foldername =~ s/\.\w{1,5}$//) {
$foldername .= '_files';
}
if (-d $foldername) {
warn "$0: directory '${foldername}' already exists...\n";
next;
}
else {
mkdir $foldername or do {
warn "$0: Can't create directory '${foldername}': $!\n";
next;
};
}
open my $fh, '<', $filename or do {
warn "$0: Can't open file '${filename}' for read: $!\n";
next;
};
my @lines;
my $num = 0;
while (defined(my $line = <$fh>)) {
push @lines, $line;
if (@lines == $lines_n or eof $fh) {
print_to_file(\@lines, $foldername, ++$num);
undef @lines;
}
}
close $fh;
}