I have one file and 2 lists
[RECORD]
Name: test1
Loc: x
Mob: y
[RECORD]
Name: test2
Loc: xx
Mob: yy
and List_old:
x
xx
List_new
0001
1110
And need to search, if 开发者_如何学JAVAfound Loc: x (x from list_old), then replace Mob: y into Mob: 0001 (0001 from new_list)
The ouput shoul be:
[RECORD]
Name: test1
Loc: x
Mob: 0001
[RECORD]
Name: test2
Loc: xx
Mob: 1110
Are all old entries of the type Mob: y
? If so, then you do not really need to correspond your replacement to Loc: x
as the Mob record is already unique.
If this is sufficient, you can use:
perl -p -i-bkup -e 's/Mob: y/Mob: 0001/g' FILE
Here is a quick-and-dirty script you can use:
#!/usr/bin/perl
die "Use: replace.pl <file> <list1> <list2>" unless $#ARGV==2;
open LIST1, $ARGV[1] or die $ARGV[1].": $!";
open LIST2, $ARGV[2] or die $ARGV[2].": $!";
open FILE, $ARGV[0] or die $ARGV[0].": $!";
while (<LIST1>) {
chomp;
$key=$_;
$value=<LIST2>;
chomp $value;
$hash->{$key}=$value;
}
while (<FILE>) {
if (/^Loc: (.*)/) {
$repl=$hash->{$1};
}
if (/^Mob: (.*)/ and defined $repl) {
s/Mob: (.*)/Mob: $repl/;
$repl=undef;
}
print;
}
close LIST1;
close FILE;
close LIST1;
A hope I understood well what you try to achieve. This script prints the result to stdout, and does not change the lines which has no corresponding pattern in the lists. Also, it assumes the lists have the same size, and overall, does very little to avoid errors.
精彩评论