Split file using perl and rename output files based on data in file

Hi there,

I have an input file that is a concatenation of multiple files (variable length).
I am trying to write a perl script that will split the concatenated file into the multiple files that it is made up of.

E.g. the input file is as follows

<start>
customer-id="100"
data 1
<end>
<start>
customer-id="200"
data 2
<end>

The text "<start>" and "<end>" always delimit the files within the input file.

So in this case there would be two new files.

I also need to name the output files with the customer-id that is containned in the data.
So the first output file would be called, for example, 100.out and it would contain
<start>
customer-id="100"
data 1
<end>

and similarly for the second and ay subsequent files

Is all of this possible?

Thanks in advance.
ghev123Asked:
Who is Participating?
 
ZiaTioNCommented:
#!/usr/bin/perl -w

use strict;

die &usage unless @ARGV;

open(FILE, "<", $ARGV[0]) || die "Can't open $ARGV[0]: $!\n";
my @data = <FILE>;
close(FILE);

my ($fName, @tmp);
for (@data) {
   push(@tmp, $_);
   $fName = $1 if (/^customer-id="(\w+)"/);
   if (($fName) && (/<end>/)) {
      my $file = $fName.".out";
      open(NF, ">", "C:\\$file") || die "Can't open $fName.out: $!\n";
      print NF $_ for (@tmp);
      close(NF);
      undef @tmp;
   }
}
print "Done!\n";

sub usage {
   my @path = split(/\//, $0);
   @path    = reverse(@path);
   my $app  = $path[0];
   print "Error! Required user input missing!\n";
   print "Usage: $app <target file>\n";
}

Pretty much the same concept as holli's, just a little more of a complete script taking user input and concatenating the file extension to the filename. Not to mention a shebang line and the needed "use strict;".
0
 
holliCommented:
open IN, "filename" or die "file not opened";

while ( <IN> )
{
      push @lines, $_;
      $id = $1 if /customer-id="([0-9]+)"/;

      if ( /<end>/ )
      {
            print "OUT $id\n";
            open OUT, ">$id" or die "cannot write";
            print OUT @lines;
            close OUT;
            @lines = ();
      }
}

close IN;
0
 
ghev123Author Commented:
Guys, this is great, many thanks for the answers. Both are very helpful.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.