How do I split file into pieces with PERL?

How do I split file into pieces with PERL?
IE
file.txt
head
1
2
3
4
end
head
5
6
7
8
9
end
n so on

Hope you mean this type of splitting...

#!/usr/local/bin/perl

use strict;
use warnings;

my $infile='file.txt';
my $count=1;
my $outfile="$infile-section_$count.txt";
my @arr;

sub create_file {
open(OUT,">$outfile") or die "Error with outfile: $!\n";  
print OUT @arr;
close(OUT);
@arr=();
$count++;
$outfile="$infile-section_$count.txt";
}

open(IN,$infile) or die "Error with infile $infile: $!\n";
my @data=<IN>;
close(IN);

 foreach my $line (@data) {
  chomp($line);

  if ($line =~ /head/) {
  push @arr, "$line\n";
  next;
  }
  elsif ($line !~ /end/) {
  push @arr, "$line\n";
  next;
  }
  else {
  push @arr, "$line\n";
  create_file();
  }
 }
$ ./cutsections.pl
$ ls file.txt-*
file.txt-section_1.txt	file.txt-section_2.txt
$
$ cat file.txt-section_1.txt
head
1
2
3
4
end
$ cat file.txt-section_2.txt
head
5
6
7
8
9
end
$
1 Like

works
I'm new to perl I can accomplish this in bash or korn
Just trying to learn perl lol

Hi, there,
I was looking for a script like the one proposed by pseudocoder.
I've given it a try and it works fine for me. But I want to repeat the process through a batch of files located in the same folder. How could I do it? Modifying the $infile value? But how? My perl knowledge is too shallow to do it myself.
Best

awk 'FNR==1{i=0}/head/{p=++i}p{print > FILENAME"-part-"i}/end/{p=0}' file*

Thank you! I've tried it, but I got this message:

By the way, might I write a regular expresion instead of head? Say,

<intervention.+?>

.

Thanks

Try:

awk 'FNR==1{i=1}/head/{p=1;if(f)close(f);f=FILENAME"-part-"i++}p{print>f}/end/{p=0}' file*

You can use extended regular expressions instead of head..

2 Likes

Thanks a lot! Now it runs smoothly. Instead of learning Perl I will start with awk. It seems an easier option to modify xml files.
Best