gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:25:10 24 4
gpt4 key购买 nike

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

我想更改脚本以遍历文件目录
也就是说,该脚本应采用以下格式,而不是提示输入和输出文件:
作为参数的目录路径,例如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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com