> -----Original Message----- > From: Jim Witte [mailto:[EMAIL PROTECTED]] > Sent: Thursday, November 29, 2001 11:09 AM > To: [EMAIL PROTECTED]; [EMAIL PROTECTED] > Subject: Elegant way to find/remove line from text file > > > Hello, > > I'm updating a script that manages the .htpasswd file on > *N*X boxes. > The user records are stored on successive lines, in the form > $username:$password. What I want to do is find a particular > $username, > then delete the entire line. > > The current code reads the entire file into an array, then loops > through every line in the array, incrementing a counter each time. If > the $username part of the line matches, splice is used to remove that > line from the area. Then the array is written back out to a new file. > > This seems inelegant to me (there should be some way to do > this in two > or three lines, this is PERL, is it not?), as well as > memory-hogging and > possibly slow (read the ENTIRE file in, even it it's the first user to > be removed?) > > What I'd like to do is read in each line, check it, if it doesn't > match, spit it out to the new file; if it does match, just > copy the rest > of the original file (sans one line) to the new file in one statement > (blockMove like operation) Is there a way to do this? > > Later on, the boss wants the script to display a list of > all users and > allow an interactive deletion utility using forms, which will > mean I'll > have to read everything into an array (or multiple - is there any > memory/speed advantage to dealing with several small arrays > rather than > one big one - say 20 in each for 20 names per page). I plan to do all > this using CGI.pm at least eventually, I may hack something together > without it until I learn it.. > > Is there a module out there for doing operations with files, like > deleteing single lines in one call like "$f = open(..); $line = > ($f->getLine(p); $f->deleteLine($q)" without having to read in in, > process it, then write it back out? A Scheme-style MAP command would > also be very useful. > > Thanks for listening to a lot of questions, > Jim Witte
First of all, there's a FAQ article on this. Read: perldoc -q 'delete a line' Second, the canonical one-liner to delete lines from a file is: perl -ni -e 'next unless /foo/' myfile.txt This deletes all lines matching /foo/. To only delete the first line matching /foo/, you need something like this: perl -ni -e 'next unless /foo/ && !$x++' myfile.txt Also, you should look at the Apache::Htpasswd module on CPAN. I've never used it, but it looks like it does exactly what you are looking for. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]