如何进行批量搜索并替换为 Perl? [英] How can I do bulk search and replace with Perl?

查看:46
本文介绍了如何进行批量搜索并替换为 Perl?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following script that takes in an input file, output file and replaces the string in the input file with some other string and writes out the output file.

我想更改脚本以遍历文件目录即不是提示输入和输出文件,脚本应该作为参数一个目录路径,例如 C:\temp\allFilesTobeReplaced\ 和搜索字符串 x 并将其替换为 y 下的所有文件目录路径并写出相同的文件.

I want to change the script to traverse through a directory of files i.e. instead of prompting for input and output files, the script should take as argument a directory path such as C:\temp\allFilesTobeReplaced\ and search for a string x and replace it with y for all files under that directory path and write out the same files.

我该怎么做?

谢谢.

$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 单行程序的使用

The use of the perl single liner

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

可以与 File::Find 结合使用,以提供以下单个脚本(这是我用于许多此类操作的模板).

can be combined with File::Find, to give the following single script (this is a template I use for many such operations).

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆