#!/opt/bin/perl -w use strict; # we want a valid positive integer for number of files to split the original file into my $fn_count = $ARGV[0]; die "Bad number of files\n" unless($fn_count =~ /^\d+$/ and $fn_count > 0); main(); exit(0); sub main{ # Work out how many lines per output file - there may be some additional lines in the final file # e.g. a 10-line file split into 3 files will be 3 lines for the first two, then 4 in the final file # also, if the result of the div is 0, then make it 1 open(IN, $ARGV[1])||die "Cannot open $ARGV[1]:$!\n"; my $lines = 0; $lines ++ while(); close IN; my $lines_per_file = int($lines/$fn_count); $lines_per_file = 1 if !$lines_per_file; # Set the current line count to 0 # and the current output file to 1 my $ln_count = 0; my $file_number = 1; # Re-open the input file open(IN, $ARGV[1])||die "Cannot open $ARGV[1]:$!\n"; # Open our first output file (original filename + _) open(OUT, ">$ARGV[1]_$file_number")||die "Cannot open $ARGV[1]_$file_number for write:$!\n"; while(){ # If we've reached our total output for this file (providing it's not the last file)... if($ln_count == $lines_per_file and $file_number < $fn_count){ $file_number ++; #...bump this up for the next file... $ln_count = 0; # ...reset line count back to 0... # ... close the current file and open the next one close OUT; open(OUT, ">$ARGV[1]_$file_number")||die "Cannot open $ARGV[1]_$file_number for write:$!\n"; } # print to the current output file print OUT $_; # inc our line count $ln_count ++; } # close the final file close OUT; }