Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
I would like to modify a line in the /etc/passwd (gcos) file after I've found it. I know you can take the file in line by line, grep the line I want, then toss that line back in modified. But does anyone know a better way of doing this WITHOUT the use of modules (so it can be used on a fresh perl install and different types of files, not just the passwd file). Thanks in advance.
  • Comment on How do I modify a single line in a file?

Replies are listed 'Best First'.
Re: How do I modify a single line in a file?
by THRAK (Monk) on Apr 20, 2001 at 23:42 UTC
    You can do this without modules. This is almost straight from the Perl Cookbook 7.10 Modifying a File in Place Without a Temporary File.
    open(F, "+< $infile") or die "Can't read $infile: $!\n"; $out= ''; while (<F>) { #find the line you want and manipulate here $out .= $_; } seek(F, 0, 0) or die "Can't seek to start of $infile: $!\n"; print F $out or die "Can't print to $infile: $!\n"; truncate(F, tell(F)) or die "Can't truncate $infile: $!\n"; close(F) or die "Can't close $infile $!\n";


    -THRAK
    www.polarlava.com
Re: How do I modify a single line in a file?
by Sprad (Hermit) on Apr 20, 2001 at 23:42 UTC
    In the FAQ.

    ---
    I'm too sexy for my .sig.

Re: How do I modify a single line in a file?
by gregor42 (Parson) on Apr 20, 2001 at 23:57 UTC

    I would like to modify a line in the /etc/passwd (gcos) file after I've found it...WITHOUT the use of modules (so it can be used on a fresh perl install

    Now we wouldn't be trying to make a hacking tool now would we?

    FYI - A Fresh PERL install comes with a lot of handy modules included.

    Here's a hint, start with:

    open(FH, "< $filename") or die ("Can't read file: $!\n"); @the_file = <FH>;

    Then you could play with the contents of @the_file & write the whole thing back out again. (Assuming you close and open(FH, "> $filename") again.

    Now AFAIK the IO module installs with a basic PERL installation. So a better way to do this might be:

    use IO::File; $fh = IO::File->new($filename, "r+") or die "Couldn't open $filename for read & write: $!\n";

    I hope I have been of some useful guidance...



    Wait! This isn't a Parachute, this is a Backpack!
Re: How do I modify a single line in a file?
by yakko (Friar) on Apr 21, 2001 at 00:41 UTC
    How about expanding this to work on NIS/YP systems? setpwent and getpwent may be of use to you, in this case.

    --
    Me spell chucker work grate. Knead grandma chicken.

Re: How do I modify a single line in a file?
by physi (Friar) on Apr 21, 2001 at 18:14 UTC
    Don't know if this is in one of the above references...
    Anyway maybe from the commandline:
    perl -p -i -e ' s/whatever/whateverelse/ if /whateveryou'relookingfor/ + ' /etc/passwd
    ----------------------------------- --the good, the bad and the physi-- -----------------------------------