in reply to Search for a BLOCK of text and selectively replace

I'm definately not an expert, but I've got a similar script that I use to parse a file in the same way. This is the code I wrote to do so, modified to work with your file. I'm sure there is a better way to do this. It puts whatever is between the *DESCRIPTION and the *END into the @description array. You can then loop over @description and do what you wish with it.
#!/bin/perl -w use strict; open (DATA, "text.txt") || die "Can't access test\n"; #each element in the array is a single line my @data = <DATA>; close(DATA); #vars to manipulate the data my $line=""; my @description = (""); my $found = "false"; #while it is not the end of the file while($line = shift @data){ chomp $line; if($line =~ "DESCRIPTION"){ $line = shift @data; chomp $line; while(!($line =~ "END")){ if(!($line =~ ";")){ push @description, $line; } $line = shift(@data); chomp $line; } print "[",@description, "]\n"; #if there's going to be more descriptions in the same file #then we can clear the array and keep going through the #file until we run out of lines. Otherwise @description #will continue to accumulate strings #@description = (""); } } if($found eq "false"){ #then we didn't find a description #add it here }
That will at least answer your first question.

Replies are listed 'Best First'.
Re(2): Search for a BLOCK of text and selectively replace
by dmmiller2k (Chaplain) on Mar 22, 2002 at 07:07 UTC

    Yours is closest to the way I would do it. My approach would probably be to use a Finite State Machine, but otherwise works the same way.

    Since Rhodium has said s/he wants to do a search and replace, I presume that the rest of the file should be preserved. For example, run this script with 'prog file >out_file':

    #!/usr/local/bin/perl -w my $inblock = 0; while (<>) { if ($inblock ) { if (/^\*END/ ) { $inblock = 0; } else { s/expression_to_find/replace_with/g; # e.g. } } elsif ( /^\*DESCRIPTION ) { $inblock = 1; } print; # print $_ implicitly }

    Nothing fancy, just does the job

    dmm

    GIVE a man a fish and you feed him for a day
    TEACH him to fish and you feed him for a lifetime
Re: Re: Search for a BLOCK of text and selectively replace
by Rhodium (Scribe) on Mar 22, 2002 at 14:30 UTC
    First off thanks a lot!

    Now, I like this one because it allows me to verify that I am in fact working on the right block. But this presents the problem that I don't know how to deal with.

    FYI - I know that I will only have one DESCRIPTION block but the stuff inside of DESCRIPTION is what may be elsewhere in the file.

    My problem is ok now I have an array @description now If do my search and replaces does this get reflected in @data? I need to play with this..

    And like you said now I need to work the "crap the variable I want to change isn't in there"