Perl读取文本文件的每一行搜索内容,如果找不到,则用新值替换它

时间:2016-01-21 15:47:04

标签: perl

我想写一个Perl脚本来搜索文件中的一行。如果找到该行,则用户可以退出,如果不是,则必须用给定的值替换该行。

以下是代码。一切都运行正常,但代码并没有替换文件中的内容。

请你纠正我出错的地方?

#!/usr/bin/perl

use strict;
use warnings;

use Config;
use Socket;
use POSIX qw(strftime);
use IO::Socket::INET;
use FileHandle;

my $filepath = "D\:\\Perl Docs and installers\\Platform\.log";

&DRbackupconfiguration( $filepath, "DRCOPY", "1000" );

sub DRbackupconfiguration {
    my ( $filepath, $parameter, $value ) = @_;

    my $status = "True";

    open my $info, $filepath or die "Could not open $filepath: $!";

    foreach ( my $line = <$info> ) {

        if ( $line =~ /$parameter/ ) {

            if ( $line ne $parameter . "/=" . $value ) {

                print "The initial parameter is $parameter \n";
                print "The initial value is $value \n";

                $line = $parameter . "=" . $value;

                open( FH, $filepath ) || die("-E- Unable to open \n");
                print( FH $line );

                print "The parameter is $parameter \n";
                print "the line is $line \n";
                close $info;

                print "$value \n";
                print "Value Changed \n";
            }
            else {
                print "Configuration already exists. Hence no changes made. /n";
            }
        }
        else {
            print "Parameter does not exist in the file \n";
            my $status = "False";
        }
    }
    close FH;
}

3 个答案:

答案 0 :(得分:0)

您是否尝试使用 sed 命令进行全局搜索和替换?只需一行shell命令就可以在文件中全局更改匹配的文本。

sed -i "s/text_to_change/text_to_put/g" filename

答案 1 :(得分:0)

据我所知,您要检查文件中是否已存在给定参数的值,如果不存在则添加

主要问题是您正在测试输入文件的每一行,并声明每次在文件中找不到该参数时该参数都不存在于文件中的任何位置其中一行

您应该通读整个文件并测试参数是否存在于任何地方。如果没有,则需要使用添加的新行重写整个文件

这应该接近你需要的

#!/usr/bin/perl

use strict;
use warnings 'all';

my $filepath = 'D:\Perl Docs and installers\Platform.log';

dr_backup_configuration( $filepath, 'DRCOPY', 1000 );

sub dr_backup_configuration {

    my ( $filepath, $parameter, $value ) = @_;

    my @log = do {
        open my $fh, $filepath or die qq{Unable to open "$filepath" for input: $!};
        <$fh>;
    };
    chomp @log;

    my $found = grep { $_ =~ /^$parameter=(.+)/ } @log;

    if ( $found ) {
        warn qq{Parameter "$parameter" already exists with value "$1". No changes made.\n};
    }
    else {

        print qq{The initial parameter is "$parameter"\n};
        print qq{The initial value is "$value"\n};

        my $newline = "$parameter=$value";

        open my $fh, '>', $filepath or die qq{Unable to open "$filepath" for output: $!};
        print $fh "$_\n" for @log, $newline;
    }
}

答案 2 :(得分:0)

谢谢大家的建议。以下是符合我目的的代码段;

             #!/usr/bin/perl

            use strict;
            use warnings;
            use Config;
            use Socket;
            use POSIX qw(strftime);
            use IO::Socket::INET;

            my $filepath = 'D:\Perl Docs and installers\test.log';
            my $parameter="";
            my $value="";

            dr_backup_configuration( $filepath, 'DRCOPY', '20');

            sub dr_backup_configuration 
            {

                my ( $filepath, $parameter, $value ) = @_;    
                open my $file, $filepath or die "Could not open file: $!";
                my @arrayTemp;
                my $i=0;   
                while (my $line=<$file>)
                {
                    if ($line=~/$parameter.*=/)
                    {
                        print "The parameter is $parameter \n";
                        my $expectedline="$parameter"."="."$value";         
                        $line =~s/^\s+|s+$//g;
                        $expectedline =~s/^\s+|s+$//g;
                        chomp($line);
                        chomp($expectedline);
                        if ($line eq $expectedline)
                        {
                            print "Paramter passed and the parameter available in the file is same \n";
                            last;
                        }
                        else
                        {
                        print "Paramter passed and the parameter available in the file are not same. Hence replacing the value \n";
                        $line = "$expectedline\n" ;
                        }
                    }        
                      $arrayTemp[$i]=$line;   
                      $i++;        
                      print "$line \n";                
                }
                open(my $fileWrite, "> $filepath") or die "$filepath";
                print $fileWrite @arrayTemp;
                close $fileWrite;
                close $file;              
             }