LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   perl: replacing a special line in a file (https://www.linuxquestions.org/questions/programming-9/perl-replacing-a-special-line-in-a-file-31245/)

markus1982 09-26-2002 12:25 PM

perl: replacing a special line in a file
 
I'm wondering if there is a easier solution to replace 1 line in a file ... this script just should change the /etc/login.defs ... any ideas?

Code:

#!/usr/bin/perl

# change min lengh of passwords
    open(FHANDLE, "/etc/login.defs");
    @file_content = <FHANDLE>;
    close(FHANDLE);
   
    for ($i = 0; $i < scalar(@file_content); $i++) {
        if (!(@file_content[$i] =~ /^#/) && (@file_content[$i] =~ /PASS_MIN_LEN/)) {
            $file_content[$i] = "PASS_MIN_LEN\t8\n";
            last; } 
    }

    open(FHANDLE, ">/etc/login.defs");
    print FHANDLE @file_content;   
    close(FHANDLE);


lackluster 09-26-2002 02:05 PM

I'd do this :

Code:

#!/usr/bin/perl

$input_file = "/etc/login.defs";
open(FIN, $input_file);
open(FOUT, ">$input_file");

while(<FIN>) {
  next if m/^#/;
  print FOUT "PASS_MIN_LEN\t8\n" and last if m/PASS_MIN_LEN/;
}

untested, but you get the idea.


All times are GMT -5. The time now is 02:22 PM.