如何替换文件中的特定字段

时间:2010-09-01 14:49:29

标签: perl

在档案中:

"name": "test","Address": "UK" "currency": "£" no:121212 ,
"name": "test1","Address": "UK" "currency": "£" no:12123212 ,
"name": "test2","Address": "UK" "currency": "£" no:121223212 ,
"name": "test3","Address": "UK" "currency": "£" no:121223212 ,
"name": "test4","Address": "UK" "currency": "£" no:121223212 ,

我想将所有的no替换成*

"name": "test","Address": "UK" "currency": "£" no:***** ,
"name": "test1","Address": "UK" "currency": "£" no:***** ,
"name": "test2","Address": "UK" "currency": "£" no:***** ,
"name": "test3","Address": "UK" "currency": "£" no:***** ,
"name": "test4","Address": "UK" "currency": "£" no:***** ,

并希望追加回文件

4 个答案:

答案 0 :(得分:3)

$ perl -pe 's/no:\d+/no:*****/' < input_file > output_file

答案 1 :(得分:3)

这个单行应该这样做:

 perl -i.bak -pe 's/(?<=no:)\d+/****/' filename

答案 2 :(得分:1)

cat input | perl -lne 's/^(.+)no:(\d+)(.*)/print"$1no:","*" x length($2),"$3"/e' > output

答案 3 :(得分:1)

我可能很想使用File::Map来更改文件。但是,如果我这样做,我必须一对一地替换数字,因为这不会移动文件中的其他字符:

use File::Map qw(map_file);

map_file my $map, 'test.txt', '+<';
$map =~ s/(?<=no:)(\d+)(?=\s*,$)/ '*' x length $1 /meg;