perl - 如何批量搜索并替换为Perl?

标签 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);

最佳答案

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

关于perl - 如何批量搜索并替换为Perl?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/918128/

相关文章:

javascript - 简单的textarea字符串替换jquery脚本

php - mysql批量处理数据

Perl,在 x 秒后使脚本超时?

perl - 当值可能是数字或字符串时,如何将列与 Perl 的 printf 对齐?

javascript - 替换 unicode 字符

ios - 如何用格式替换字符串中的空格

linux - 如何在 %% 或 $$ 中间 grep/split 一个词

Perl::Critic 'Code before strictures' 使用 Modern::Perl 时

javascript - Mongoose 批量插入遗漏了关键信息

MySQL批量权限