2009-05-27 46 views
6

我有下面的腳本,需要在輸入文件,輸出文件和 用其他字符串替換輸入文件中的字符串,並輸出 輸出文件。如何進行批量搜索並用Perl替換?

我要改劇本通過文件 即不是提示輸入和輸出文件的目錄遍歷,腳本應該採取 作爲參數的目錄路徑,如C:\ TEMP \ allFilesTobeReplaced \和 搜索對於字符串x並將其替換爲y,以獲取目錄路徑下的所有文件並寫出相同的文件。

我該怎麼做?

謝謝。

$file=$ARGV[0]; 

open(INFO,$file); 
@lines=<INFO>; 
print @lines; 

open(INFO,">c:/filelist.txt"); 

foreach $file (@lines){ 
    #print "$file\n"; 
    print INFO "$file"; 
} 

#print "Input file name: "; 
#chomp($infilename = <STDIN>); 

if ($ARGV[0]){ 
    $file= $ARGV[0] 
} 

print "Output file name: "; 
chomp($outfilename = <STDIN>); 
print "Search string: "; 
chomp($search = <STDIN>); 
print "Replacement string: "; 
chomp($replace = <STDIN>); 

open(INFO,$file); 
@lines=<INFO>; 
open(OUT,">$outfilename") || die "cannot create $outfilename: $!"; 

foreach $file (@lines){  
    # read a line from file IN into $_ 
    s/$search/$replace/g; # change the lines 
    print OUT $_; # print that line to file OUT 
} 
close(IN); 
close(OUT); 

回答

11

使用perl的單排的

perl -pi -e 's/original string/new string/' filename 

可以File::Find結合,給下面的單個腳本(這是一個模板,我用了很多這樣的操作)。

use File::Find; 

# search for files down a directory hierarchy ('.' taken for this example) 
find(\&wanted, "."); 

sub wanted 
{ 
    if (-f $_) 
    { 
     # for the files we are interested in call edit_file(). 
     edit_file($_); 
    } 
} 

sub edit_file 
{ 
    my ($filename) = @_; 

    # you can re-create the one-liner above by localizing @ARGV as the list of 
    # files the <> will process, and localizing $^I as the name of the backup file. 
    local (@ARGV) = ($filename); 
    local($^I) = '.bak'; 

    while (<>) 
    { 
     s/original string/new string/g; 
    } 
    continue 
    { 
     print; 
    } 
} 
1

我知道你可以使用一個簡單的每l命令行中的單行命令,其中文件名可以是單個文件名或文件名列表。你也許可以用BGY的回答結合本以獲得所需的效果:

perl -pi -e 's/original string/new string/' filename 

而且我知道這是老生常談,但這聽起來像sed,如果你可以使用GNU工具:

for i in `find ./allFilesTobeReplaced`; do sed -i s/original string/new string/g $i; done 
2

您可以用-i PARAM做到這一點:

只是處理所有的文件作爲正常的,但包括-i.bak:

#!/usr/bin/perl -i.bak 

while (<>) { 
    s/before/after/; 
    print; 
} 

這應該處理每一個文件,將原文重命名爲original.bak當然,您可以像@Jamie Cook所提到的那樣將其作爲一行提供。

-1

perl -pi -e##舊#新#g'文件名。 您可以用適合您的文件列表的模式替換文件名。