echow has asked for the wisdom of the Perl Monks concerning the following question:

This node falls below the community's threshold of quality. You may see it by logging in.

Replies are listed 'Best First'.
Re: Splitting up lines in a few files
by GrandFather (Saint) on Nov 09, 2005 at 08:15 UTC

    What have you tried? The general form of the thing is open your input file then enter a loop while there is more to read from the input file. In the loop open the next output file, copy n lines from the intput file to the output file, close the output file, continue with the next output file. When you exit the loop, close the input file. Where do you have difficulty with that?


    Perl is Huffman encoded by design.
Re: Splitting up lines in a few files
by tirwhan (Abbot) on Nov 09, 2005 at 08:25 UTC
    GrandFather already gave you the general-purpose perl answer. If you're on a *NIX, you can use the utility split for this.
    split -l 2000 C prefix

    will take a file called C and split it into files called prefixaa prefixab prefixac etc., each containing 2000 lines from C. See man split for more details.


    Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -- Brian W. Kernighan
Re: Splitting up lines in a few files
by holli (Abbot) on Nov 09, 2005 at 09:19 UTC
    >perl -ne "BEGIN{open F,'>0.txt'}print F $_;unless($.%5){close F;open +F,'>'.($./5).'.txt';}" file.txt


    holli, /regexed monk/

      The filehandle will be closed when you open it again so you don't have to do that explicitly.

      Here is a variation:

      perl -ne '$n=$.-1; open F, ">$n.txt" unless $n%5; print F' file Creates: 0.txt 5.txt 10.txt ...

      This omits IO checking for the sake of a one-liner.

      Here is a slightly longer one but with better output filenames:

      perl -ne 'BEGIN{$s="file000"} open F, ">". $s++. ".txt" unless ($. +-1)%5; print F' file Creates: file000.txt file001.txt file002.txt ...

      Although, realistically I'd use split for this task as shown by tirwhan above.

      --
      John.