split_to_n_lines.pl 1.5 KB

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