我有2个文件我希望将file1
中的值与file2
进行比较,如果找到的值与file1
不同,则替换file2
的值。
如果file2
中有任何其他值,则可以忽略它。
file1
:
value1 equalto txt
value2 equalto doc
value3 equalto new
file2
:
value1 equalto doc
value2 equalto ref replace this value in file1
value3 equalto txt replace this value in file1
value4 equalto test ignore this if not found in file1
答案 0 :(得分:0)
#!/usr/bin/env perl
use strict;
use warnings;
my $ pass = 0;
my ( $first, $rest, %hash_of_lines );
while (<>) {
chomp;
( $first, $rest ) = split / /, $_, 2;
if ($pass == 0) {
$hash_of_lines{$first} = $_;
}
elsif ( exists $hash_of_lines{$first} ) {
$hash_of_lines{$first} = $_;
}
$pass++ if eof;
}
for my $key (sort keys %hash_of_lines) {
print $hash_of_lines{$key}, "\n";
}
1;
使用它:
$ ./build file1 file2
答案 1 :(得分:0)
这应该可以解决问题:
#!/usr/bin/perl
use strict;
use warnings;
my ($to_change, $reference) = @ARGV[0,1];
my %pairs_ref;
my %pairs_change;
my $line = qr/^(\w+)\s+equalto\s+(\w+)/;
# read the reference file
open (my $fhr, '<', $reference) or die "Cannot read from file $reference: $!";
while (<$fhr>) {
if (/$line/) {
my ($param, $value) = ($1, $2);
$pairs_ref{$param} = $value; # store all pairs
}
}
close $fhr;
# read the file to be modified (note: we're not using in-place modification!)
open (my $fhc, '<', $to_change) or die "Cannot read from file $to_change: $!";
while (<$fhc>) {
if (/$line/) {
my $param = $1;
# if the parameter appeared in the reference file, set the value to the reference
# value (does no damage if they're identical anyway)
if (defined $pairs_ref{$param}) {
$pairs_change{$param} = $pairs_ref{$param};
}
}
}
close $fhc;
# print to the output file (that way we're not overwriting the original information)
open (my $fhn, '>', "file3") or die "Cannot write to file3: $!";
foreach my $param (sort keys %pairs_change) {
print $fhn "$param equalto $pairs_change{$param}\n\n";
}
close $fhn;
这很简单,我只使用了你问题中给出的信息,所以我不知道这是否确实是你正在寻找的。我没有考虑空格数量的差异。
生成的文件(我称之为'file3')如下所示:
value1 equalto doc
value2 equalto ref
value3 equalto txt
脚本将被调用如下:
./script.pl file1 file2