2009-05-27 86 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'文件名。 您可以用适合您的文件列表的模式替换文件名。