• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 410
  • Last Modified:

Parsing a flat file, how to create a csv file

I have a very large file that looks (more or less) like:

I: Steve
1234 Oak
Apt 5
City
I: Jack
99 Elm
Town
I: Dave
123 Pine
Suite 444
Mail stop 5
Village

And I want it to look like:

Steve, 1234 Oak, Apt 5, City
Jack, 99 Elm, Town
Dave, 123 Pine, Suite 444, Mail stop 5, Village

Each block of customer data begins with an "I:" and is followed by a name. Basically, if every "block" of data was the same number of lines, say 4, I'd just loop through the file and create a "record" for every four lines of the file. But in my file, some of the "blocks" are 3 lines and some are as much as 10. I know a new "block" begins with an "I:", but I cant figure out . . . well, hopefully you get the idea.

This is a one-time task, so a quick and dirty solution is fine.

Thanks
Steve
0
Steve Jennings
Asked:
Steve Jennings
3 Solutions
 
svgmucCommented:
local $/='I:';
open FILE, "myfile" or die "Couldn't open file: $!";
binmode FILE;
while (<FILE>) {
    $record = $_;
    chomp $record;
    $record =~ s/\n/,/;
}
close FILE;
0
 
wilcoxonCommented:
This will work...
#!/usr/local/bin/perl

use strict;
use warnings;

my @data;
while (<DATA>) {
        chomp;
        if (/^I:\s+(.*)$/) {
                my $name = $1;
                if (@data) {
                        print join(', ', @data), "\n";
                        @data = ();
                }
                push @data, $name;
        } else {
                push @data, $_;
        }
}
if (@data) {
        print join(', ', @data), "\n";
}

__DATA__
I: Steve
1234 Oak
Apt 5
City
I: Jack
99 Elm
Town
I: Dave
123 Pine
Suite 444
Mail stop 5
Village

Open in new window

0
 
FishMongerCommented:
svgmuc has the right idea, but has a couple problems.

Try this:

#!/usr/bin/perl

use strict;
use warnings;

$^I = '.bak';
$/ = 'I: ';

@ARGV = 'file.txt';

while ( <> ) {
    chomp;
    my @fields = split /\n/;
    print join(',', @fields), "\n";
}

Open in new window

0
 
Steve JenningsIT ManagerAuthor Commented:
Thanks to all. Done and done.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now