Splitting large text file on every blank line

后端 未结 9 939
南方客
南方客 2020-12-05 07:53

I\'m having a bit trouble of splitting a large text file into multiple smaller ones. Syntax of my text file is the following:



        
9条回答
  •  一向
    一向 (楼主)
    2020-12-05 08:34

    Perl has a useful feature called the input record separator. $/.

    This is the 'marker' for separating records when reading a file.

    So:

    #!/usr/bin/env perl
    use strict;
    use warnings;
    
    local $/ = "\n\n"; 
    my $count = 0; 
    
    while ( my $chunk = <> ) {
        open ( my $output, '>', "filename_".$count++ ) or die $!;
        print {$output} $chunk;
        close ( $output ); 
    }
    

    Just like that. The <> is the 'magic' filehandle, in that it reads piped data or from files specified on command line (opens them and reads them). This is similar to how sed or grep work.

    This can be reduced to a one liner:

    perl -00 -pe 'open ( $out, '>', "filename_".++$n ); select $out;'  yourfilename_here
    

提交回复
热议问题