Click to See Complete Forum and Search --> : Perl: removing a line from file


flar
08-13-2003, 09:01 PM
just a quick help..

I'm almost done with this one..but this last thing..

How do i remove a line from a file(FILEHANDLE)?


thanks in advance!

saithan
08-13-2003, 09:44 PM
read the file into an array

open FILE, "/path/to/file" or die ("problem opening the file ");
@thefile = <FILE>;
close FILE;


now the file is divided into lines, each line is an element in the array.

I now delete the 3rd line in the array by calling that element.
(note that line 1 is element 0 in the array)
$thefile[2] = "";

you then reopen the file handle to write/replace (>).

open FILE, ">/path/to/file" or die ("could not write file");
foreach (@thefile){
print FILE "$_ ";
}
close FILE;


This is only a fast dirty way to do the job, with expresions you can be a lot more accurate in what lines and patterns you wantto manipulate.

o0zi
08-14-2003, 03:53 PM
Let $line be the text of the line you want to remove:

#!/usr/bin/perl -w
open (FILE, "/path/to/file");
@filearray=<FILE>;
for ($i=0;$i<=@filearray;$i++) {
if ($filearray[$i] eq $line) {
@splicea =splice(@filearray, 0, $i-1);
@spliceb =splice(@filearray, $i+1,$#filearray);
@filearray = (@splicea, @spliceb);
}
close (FILE);
open (OUTFILE, ">/path/to/file");
print OUTFILE split(@filearray, "\n");
close (OUTFILE);

I'm a bit rusty on my Perl, but I think that should work. There's probably an easier way.

dchidelf
08-14-2003, 09:49 PM
If the file you were removing a line from was sufficiently large, reading the file into an array would be a bad idea, it would waste a great deal of memory. For small files it works great because you can move all sorts of things in memory, sort the lines, whatever.

If you work with large files you should instead process each line as it is read from the file.


#!/usr/bin/perl -w
## remove line 3 from file
my $file = "/path/to/file";
open (IN, $file);
unlink($file); # prevents the next open from truncating the file
open(OUT, ">$file");
while(<IN>){
### whatever logic to eliminate lines
print OUT unless($. == 3);
}
close (IN);
close (OUT);


You would definitely want to add error checking especially to the first open to make sure the file opened correctly, otherwise the unlink will wipe out your file.

saithan
08-14-2003, 10:49 PM
I agree on that dchidelf,

that is why I stated that it was a quick and dirty way.

the array can get big on large files.

I really like the speed of what you are showing in your example.

saithan
08-14-2003, 10:49 PM
ackkk, accidentally posted twice.

flar
08-19-2003, 06:22 AM
hey thanks bro's!!

what i really wanna achieve is to create my own web-based administration for SQUID-proxy user authentication..

1. i wanted to add different groups so i could manage user access easily..

2. so i could add/delete/deactivate/reactivate users in just a click on my mouse :)

and i just finished it! :D

thanks again! :D