在多个文件中搜索模式,并将现有匹配替换为增量

时间:2014-12-09 11:27:43

标签: perl

我有大约200个文件,所有文件都有相同的值。现在想要搜索模式和 替换匹配字符。

示例:

file01.txt

1,51:495600    
118,1:20140924105028    

file02.txt have    
1,51:495600    
118,1:20140924105028    

......等等file200.txt

我们的结果应该是:

file01.txt

1,51:495601  /* each file ':number' will be incremented by one    
118,1:20140924105228 /* each file 11th and 12th position character will be incremented  by 02    

file02.txt

1,51:495602  /* each file ':number' will be incremented by one    
118,1:20140924105428 /* each file 11th and 12th position character will be incremented  by 02 

for earlier it was 50 now it will incremented by 52 , 53 , 54 like that max will be  60    
e.g..
file01.txt     
118,1:20140924105028 ;    
file02.txt     
118,1:20140924105228 ;    
file03.txt     
118,1:20140924105428 ;    
file04.txt     
118,1:20140924105628 ;    
file05.txt    
118,1:20140924105828 ;    

由于我是Perl的新手,我需要帮助来创建脚本。

查找以下脚本。

foreach $file (@files)
{
  open(file , "$file");    #open file
  while($line = <file>)       #read file
  {
    print "$line" if $line =~ /1,51:495600/;       #find patten
    perl -pi'.backup' -e 's/(^1,51:495600)/^1,51:/g' $file
    #find and replace and take a backup of file
  }
  close;
}

1 个答案:

答案 0 :(得分:0)

这会按照你的要求行事。它使用Time::Piece模块来操作日期/时间字段,以便正确处理小时边界和中午。这是Perl 5版本10以来的核心模块,因此不需要安装。

use strict;
use warnings;
use 5.010;     # For autodie and regex \K
use autodie;

use Time::Piece;
use Time::Seconds qw/ ONE_MINUTE /;

use constant DATE_FORMAT => '%Y%m%d%H%M%S';

my $n;

for my $file (@files) {

  open my $in_fh, '<', $file;
  my @lines = <$in_fh>;
  close $in_fh;

  ++$n;
  $lines[0] =~ s/^\d+,\d+:\K(\d+)/$1+$n/e;
  $lines[1] =~ s{^\d+,\d+:\K(\d+)}{
    my $tp = Time::Piece->strptime($1, DATE_FORMAT);
    ($tp + ONE_MINUTE * 2 * $n)->strftime(DATE_FORMAT);
  }e;

  my $backup = "$file.backup";
  unlink $backup if -f $backup;
  rename $file, $backup;

  open my $out_fh, '>', $file;
  print $out_fh @lines;
  close $out_fh;
}