我有以下脚本,它接收输入文件,输出文件并用其他字符串替换输入文件中的字符串并写出输出文件.
我想更改脚本遍历文件目录,即不是提示输入和输出文件,脚本应该将目录路径作为参数,例如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);
Run Code Online (Sandbox Code Playgroud)
Bea*_*ano 11
使用perl单衬垫
perl -pi -e 's/original string/new string/' filename
Run Code Online (Sandbox Code Playgroud)
可以结合使用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;
}
}
Run Code Online (Sandbox Code Playgroud)