[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Splitting up a text file



>        Say I have an ASCII text file with about 40,000 or more lines. I'd
>        like to split that file into smaller files, each with 10,000
>        lines.

Been thinking about that for a while, might as well try it.  Here goes:

#!perl

$max_lines = 50;    # Max lines per output file
$suffix = '1';      # Suffix for output files.  Magical.
$sep = '.';         # Separator.  Output names will be of the form:
                    #   file$sep$suffix


foreach $file (@ARGV) {
    open(FILE, $file)
        || print STDERR "Couldn't open $file\n", next;

    $suf = $suffix;

    $outfile = $file . $sep;

    open(OUT, ">$outfile$suf")
        || die "Couldn't open output file $outfile$suf";
    $line = 0;
    while (<FILE>) {
        if ($line >= $max_lines) {
            # New output file
            close OUT;
            $suf++;
            open(OUT, ">$outfile$suf")
                || die "Couldn't open output file $outfile$suf";
            $line = 0;
        }

            # Uncomment following 'if' to add criteria
#        if (/^([^\t]*\t){3}123/) {    #<--Your criteria go there.
            $line++;
            print OUT;
#        }
    }
    close OUT;
    close FILE;
}



Seems to work for me...

Pete

________________________________________________.__._.._ . _ .. .   .
Today I made a Black Forest cake out of five pounds of cherries and
a live beaver, challenging the very definition of the word cake. I
was very pleased.