Home: Perl Programming Help: Intermediate:
Removing a single line from a file


Feb 14, 2001, 6:30 PM

Views: 1630
Removing a single line from a file


I need to remove a single line from a flat file database (separated by ||):

the first data field would be the submission ID number like:

0001||Someones Name||Someones email
0002||another name||another email
0003||persons name||persons email

I want to remove the record with the ID of 0002, leaving the database as:

0001||Someones Name||Someones email
0003||persons name||persons email

How can I do this? I need to search for the ID (or any string really) and then remove the line that that ID is located on.

Thanks a lot,



Feb 15, 2001, 12:24 PM

Views: 1624
Re: Removing a single line from a file

If you're not worried about concurrent access to the file then you can do this.

my $delete_id = "0002";
# open your database file.
open(FILE, "<filename.ext") || die("Could not open database file.");
# open your output file, because you don't want to write read and write from/to a
# file with variable length records in it.

open(OUTPUT, "<output.ext") || die("Could not open output file.");
my $line = "";
while($line = <FILE>) {
my @data = split(/\|\|/, $line); # split your data up
my $id = $data[0]; # just for readability, store your 'id' in $id.
# compare to the record to delete, if a match then don't write it to the output file.
next if($id eq $delete_id);
print OUTPUT join("||", @data); # join the data of lines that pass and then print them.
} # end while loop.
close FILE;
close OUTPUT;
rename(output.ext, filename.ext); # overwrite your database file with the output file.


Feb 15, 2001, 12:38 PM

Views: 1622
Re: Removing a single line from a file


I'll play with it, but it seems like there should be a simpler way!




Feb 15, 2001, 3:14 PM

Views: 1619
Re: Removing a single line from a file

That's probably one of the better ways to do it. Unless you want to use bad code like...

open (FILE, "file.txt") || die $!; 
@youshouldntusethis = <FILE>;
close (FILE);

foreach $line (@youshouldntusethis) {
$line =~ s/$checkfor//g;

open (FILE, ">file.txt") || die $!;
print FILE @youshouldntusethis;
close (FILE);

Which is crap.

Jeffrey "muinatit" Lamoureux


Feb 20, 2001, 7:35 AM

Views: 1601
Re: Removing a single line from a file

You did NOT check the FAQ before posting this question. Please make an effort to do so in the future.

japhy% perldoc -q 'delete a line'

Found in /usr/local/lib/perl5/5.00502/pod/perlfaq5.pod

How do I change one line in a file/delete a line in a file/insert a line
in the middle of a file/append to the beginning of a file?

You can use Perl's in-place editing which looks transparent:

local ($^I, @ARGV) = ("", $filename);
while (<>) {
next if $id == (/(.*?)\|\|/)[0]; # way to test if this line has the ID

Jeff "japhy" Pinyan -- accomplished hacker, teacher, lecturer, and author