perl 遍历指定目录下的所有文件,替换指定文本内容,返回受影响的文件路径

时间:2023-03-09 04:04:53
perl 遍历指定目录下的所有文件,替换指定文本内容,返回受影响的文件路径

不会读取 影藏文件

main

#!/usr/bin/perl
use autodie;
use utf8;
use Encode qw(decode encode); if(@ARGV ne 3){ # 检查参数
$err = <<"err";
The script execution parameters are wrong! !
path, "suffix", "old value/new value"
err
die $err;
} # path, suffix, reg
my ($path, $suffix, $rp) = @ARGV;
@suffix = split " ", $suffix; # 记得把字符串,转化为数组 sub search_file{
my ($fname, $rp) = @_;
my ($o) = split("/", $rp);
open of, "<", $fname;
while(<of>){
chomp;
if($_ =~ /$o/){
return !!1;
}
}
return !!0;
} sub change_file{
my ($fname, $rp) = @_; # 获取操作文件名 和 替换的正则
if( !search_file($fname, $rp) ){ # 不存在关键字直接返回
return !!0;
} my @data = ();
my ($o, $n) = split("/", $rp);
open of, "<", $fname;
while(<of>){
chomp;
$_ =~ s/$o/$n/;
push @data, $_;
} open wf, "+>", $fname;
print wf @data;
return !!1;
} sub scan_file{
my ($path) = @_;
my @files = glob($path);
foreach my $file (@files){
if(-d $file){ # 文件递归下去
scan_file("$file/*");
}elsif(-f $file){
foreach my $su (@suffix){
if($file =~ /$su$/){ # 文件后缀在匹配范围
if(change_file($file, $rp)){ # 收集受到影响的文件路径
print "$file\n";
}
}
} }
}
} scan_file($path);

执行

λ perl main.pl "./test/*" ".txt .html .js" ajanuw/world
./test/ajanuw.txt
./test/dist/bundle.html
./test/src/index.js