Jethro, you are the man.
You saved my day, the concept of Finite-state machine is
perfect!
I modified a little few things and the script now works.
living and learning.
thanks again brother
here is the final script:
#! /usr/local/bin/perl # must add service_description inside "define service{" only in defini +tions that do not have it #Version 6 my $state="outside"; my @servicelines; my $desc_flag; #is 1 if description found(already exists, if i +ts 0 then call parse and output sd) my $file = "<test.txt"; my $sd = ""; open (MYFILE, '>services2.cfg'); open (TEXT_FILE, $file) || die "Can't open $file for read: $!"; while ($line = <TEXT_FILE>) { if ($state eq "outside") { if ($line=~/^\s*define service/) { $state="inside"; @servicelines=(); #reset array push(@servicelines,$line ); $desc_flag=0; } } elsif ($state eq "inside") { if ($line=~/^\s*}/) { if ($desc_flag eq 0){ foreach $l(@servicelines) { if ($l=~/^\s*use/) { $sd = removesem($l); #print $sd; push(@servicelines,$sd); } } } push(@servicelines, "}\n"); # go thru entire array and print to file foreach $i(@servicelines) { print $i; print MYFILE $i; } $state="outside"; } elsif ($line=~/^\s*service_description/) { push(@servicelines, $line); $desc_flag=1; } else { push(@servicelines, $line); } } } close (TEXT_FILE); close (MYFILE); sub removesem($) { my $use = shift; $use =~ s/use/service_description/; #print "test: " . $use . " \n"; if($use =~ m/sem/ ) { #remove sem $use =~s/sem_//; return $use; }else{ return $use; } } # Perl trim function to remove whitespace from the start and end of th +e string sub trim($) { my $string = shift; $string =~ s/^\s+//; $string =~ s/\s+$//; return $string; }
In reply to Re^4: How to parse a text file
by xoroz
in thread How to parse a text file
by xoroz
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |