如何进行批量搜索并用Perl替换?

时间:2009-05-27 21:35:28

标签: perl replace bulk

我有以下脚本,它接受输入文件,输出文件和 用其他字符串替换输入文件中的字符串并写出 输出文件。

我想将脚本更改为遍历文件目录 即,脚本应该采取,而不是提示输入和输出文件 作为参数的目录路径,如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);

5 个答案:

答案 0 :(得分: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 :(得分:2)

您可以使用-i param执行此操作:

正常处理所有文件,但包括-i.bak:

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

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

这应该处理每个文件,并将原始文件重命名为original.bak当然,你可以像@Jamie Cook所提到的那样做一个单行程

答案 2 :(得分:1)

试试这个

#!/usr/bin/perl -w

@files = <*>;
foreach $file (@files) {
  print $file . '\n';
}

另请参阅Perl中的glob:

答案 3 :(得分:1)

我知道你可以在命令行中使用一个简单的Perl单行程序,其中filename可以是单个文件名,也可以是文件名列表。您可以将其与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

答案 4 :(得分:-1)

perl -pi -e's#OLD#NEW#g'filename。 您可以使用适合您的文件列表的模式替换filename。

相关问题