in reply to Re^5: How do I use grep in a script
in thread How do I use grep in a script

Assuming your data is like this (numeric account ids)

Acct:1234
1
2
3
Acct:2345
2
3
4

then you could use a hash of arrays (HOA) (see perldsc) to split the file into parts.

#!/usr/bin/perl use strict; my $acct; my %data = (); my $infile = 'Facs_Data.txt'; open my $fh,'<',$infile or die "Could not open '$infile' : $!"; while (<$fh>){ next unless /\S/; # skip blank lines if (/Acct:(\d+)/){ $acct = $1; } push @{$data{$acct}},$_ if ($acct); } close $fh; for my $acct (keys %data){ my $outfile = $acct.'_2017.txt'; print "Creating $outfile\n"; open my $fh,'>',$outfile or die "Could not open '$outfile' : $!"; for (@{$data{$acct}}){ print $fh $_; } close $fh; }
poj

Replies are listed 'Best First'.
Re^7: How do I use grep in a script
by Flintlock (Novice) on Dec 27, 2017 at 14:19 UTC
    Thank you poj - as one might expect there has been an additional request for this. Now I am being asked to include a second variable in the outfile name.

    from this code

    for my $acct (keys %data){ my $outfile = $acct.'_2017.txt';

    I need to add the last name (Name:LastName FirstName) which located on the same line in the $infile, but could also be in other places in the block of text being written to the $outfile. So now the $outfile name would look like this: LastName_1234_2017.txt.

    Any suggestions on how and where I should define this new variable?

      You can add the name onto the existing $acct variable

      while (<$fh>){ next unless /\S/; # skip blank lines if (/Acct:(\d+)/){ $acct = $1; if (/Name:([^\s]+)/){ $acct = $1.'_'.$acct; } } push @{$data{$acct}},$_ if ($acct); }
      poj
        Here is my code. The addition to $acct is not adding the LastName as expected. Ideas??

        #!/usr/bin/perl use strict; my $acct; my $nam; my %data = (); my $infile = 'Facs_Data.txt'; open my $fh,'<',$infile or die "Could not open '$infile' : $!"; while (<$fh>){ next unless /\S/; # skip blank lines if (/Acct:(\d+)/){ $acct = $1; if (/Name:([^\s]+)/){ $acct = $1."_".$acct; } } push @{$data{$acct}},$_ if ($acct); } close $fh; for my $acct (keys %data){ my $outfile = $acct.'_2017.txt'; print "Creating $outfile\n"; open my $fh,'>',$outfile or die "Could not open '$outfile' : $!"; for (@{$data{$acct}}){ print $fh $_; } close $fh; }
Re^7: How do I use grep in a script
by Flintlock (Novice) on Dec 26, 2017 at 22:05 UTC
    wow !!!

    That was PERFECT !!!!

    Thank you so MUCH !!!