Gossamer Forum
Home : General : Perl Programming :

Search & Delete

Quote Reply
Search & Delete
I'd appreciate help for the following:

Goal: Search a data file (lines delineated by carriage returns) for a given string. If found, delete line from file.

What I'm doing now is to load the file into an array and then going through the array one line at a time. If not equal the search term, the line is written to a backup file. If equal, the line is omitted and the line is saved to a variable for later use. Then the file is saved as the original data file.

So if the data file is:

apples
oranges
bananas
watermelons

and the search term is bananas then the resultant file would be:

apples
oranges
watermelons

and $deleted = bananas.

There must be a better way using an array function (like push) and reg exp.

Any suggestions?

Thanks... Dan Smile
Quote Reply
Re: Search & Delete In reply to
I dunno if it's the "correct" way of doing it, but the way I do it is:

Open the file for reading. Using a foreach loop, remove the line break with chomp(). Offer up the search term to the line. If it matches, use next() to skip to the next line. If it doesn't, place it in a new variable using .=, adding a line break. Then open the file again, this time for writing, and write the new variable to it. All done. Something like this:

Code:
open(FILE,"$file") or die "Can't open file - $file - for reading";
@lines = <FILE>;
close(FILE);

foreach $line (@lines) {
chomp $line;
if ($search_term eq $line) { next; }
else { $newlines .= "$line\n"; }
}

open(FILE,">$file") or die " Can't open file - $file - for writing";
print FILE $newlines;
close(FILE);

I just lobbed that in there, so there may be syntax errors, but you get the jist...

adam
Quote Reply
Re: Search & Delete In reply to
Thanks Adam! Not quite what I'm looking for but it will suffice - it is much better than opening a backup file to write the new data and then renaming the file.

Thanks again... Dan Smile
Quote Reply
Re: Search & Delete In reply to
No problem. What were you looking for? if it's not too complicated, I might be able to help...

adam
Quote Reply
Re: Search & Delete In reply to
I meant in terms of arrays and array functions like push. But this works fine. No reason to complicate things Wink Thanks again!

Dan Smile