将字符串从一个文件替换为其他文件

时间:2011-12-21 09:55:20

标签: perl

open (HAN1, "<test1.txt") || die "not existing!";
open (HAN2, "test2.txt") || die "not existing!";

s/nameserver/nameserver/g;

    print  HAN2 $_;
    }
close(HAN1);
close(HAN2);

test1.txt

nameserver 10.66.80.10
nameserver 10.66.80.11
nameserver 10.66.80.11

的test2.txt

search test.com
nameserver 99.66.80.10
nameserver 98.66.80.11
nameserver 98.66.80.11  

运行脚本test2.txt后,删除其他字符串内容。

nameserver 10.66.80.10
nameserver 10.66.80.11
nameserver 10.66.80.11

但想要结果test2.txt

search test.com
nameserver 10.66.80.10
nameserver 10.66.80.11
nameserver 10.66.80.11

1 个答案:

答案 0 :(得分:1)

试试这个,

    use strict;
    use warnings;
    use Data::Dumper;

    open (HAN1, "<test1.txt") || die "not existing!";
    open (HAN2, "<test2.txt") || die "not existing!";

    my $current;
    my @arr1 = <HAN1>;

    foreach $current (<HAN2>) {
        unless ($current =~ /nameserver/) {
            print $current;
            next;
        }
        foreach  (@arr1) {
            my($first,$second) = split (' ',$_);
            $current =~ s/^(nameserver\s+).+/$_/g;
            chomp($current);
            print $current;
            last;
        }
        shift @arr1;
    }
close(HAN1);
close(HAN2);