我有以下脚本,它接受输入文件、输出文件和
将输入文件中的字符串替换为其他字符串并写出
输出文件。
我想更改脚本以遍历文件目录
即,脚本不应提示输入和输出文件,而应采用
作为参数的目录路径,例如 C:\temp\allFilesTobeReplaced\ 和
搜索字符串 x 并将其下的所有文件替换为 y
目录路径并写出相同的文件。
我该怎么做呢?
Thanks.
$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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)