2014-12-09 89 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

相關問題