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

Hi i have a problem that is similar to one above. Ex I have this file that contains:
John Smith|mypassword|4/23/67
lisal Slks|passwd|872/24/123 (whatever)

so how do i make to find a simple person and extract the info and replace it?

Edit kudra, 2001-10-02 Changed title; added formatting

Replies are listed 'Best First'.
Re: Passwd file
by chromatic (Archbishop) on Oct 02, 2001 at 01:15 UTC
Re: Passwd file
by C-Keen (Monk) on Oct 02, 2001 at 01:20 UTC
    You could be scanning through the file line for line and look for the name you want, (use the matching operator), split the line with 'split' modify your information delete the old line and add the new one. This might look something like this:

    #!/usr/bin perl -w use strict; my $passfile = shift || 'passfile'; my $wantedname = shift || 'John Doe'; my $newpass = shift || '1234'; # example for changing a value my $tempfile = $passfile.'temp'; # file where we copy all info for rem +oving a line my $searchstr = shift || 'abcd'; my $line; # line of the passfile #first open the file open(PFILE,"<$passfile") or die "unable to open $passfile, because $!\ +n"; #second open our tempfile open(TEMP,">$tempfile") or die "unable to open $tempfile, because $!\n +"; while ($line = <PFILE>){ if ($line =~m/$wantedname/){ print "Changing $line to "; #assume we now that we want to change the second element if we don +'t a comparison will be easily implemented if($line =~s/$searchstr/$newpass/){ #put data back together print $line."\n"; # display line on screen } } print TEMP $line; # write line to temp file } #close original file close PFILE or die "unable to close $passfile,because $!\n"; die "unable to delete $passfile, because $!\n" if (!unlink($passfile)) +; # rename temp file to original file rename $tempfile, $passfile or die "unable to rename file, because $!\ +n"; #done print "\ndone.\n";

    This does not work if the name is not unique or the value that you want to chang isn't.But anyway it is something :-)

    Hope this helps,
    C-Keen

Re: Passwd file
by jlongino (Parson) on Oct 02, 2001 at 05:36 UTC
    I can't add much to what's already been posted except that you should use code tags where appropriate in your submission. E.G.,
    <code>
    John Smith|mypassword|4/23/67
    lisal Slks|passwd|872/24/123
    </code>
    
    You will get more timely responses and your posts will be approved much more quickly since they won't have to be edited first. This information is covered in Site How To.

    "Make everything as simple as possible, but not simpler." -- Albert Einstein