2014-12-09 84 views
-1

替换现有的匹配递增我有大约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; 
} 
+0

请解释第二条线的行为。字符11和12是'50'。这听起来像你想在第一个文件中添加2,在第二个文件中添加3,但你的*例子*在第一个文件中添加2,在第二个文件中添加4,在第三个文件中添加6。 “最大值将是60”*?这个字段在'file09.txt'(或'file05.txt'取决于算法)达到'60'后会发生什么。 – Borodin 2014-12-09 13:29:38

+0

118,1:20140924105028 如果我们打破字段“20140924105028”,它可以是以下理解如所提到的: \t YYYY\t毫米\t \t DD HH24 \t \t MI SS 现在想法是增加分钟(这是在上述的情况下为50)通过2分钟直到它达到〜60。一旦达到60,小时柱应由另外1小时增加(在这种情况下将是11)和所述分钟计数器应该从00,02,04,... 60开始。 实施例: - 118,1:20140924105228 118,1:20140924105428 118,1:20140924105628 118,1:20140924105828 118,1:20140924110028 118,1:20140924110228 。 。 。 等等。 – 2014-12-09 15:01:42

回答

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; 
} 
+0

使用'perl,v5.10.1'我得到'全局符号“@files”需要明确的包名在......第13行。 – Armali 2017-03-28 11:03:40

相关问题