加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl脚本递归替换所有指定目录指定文件类型中的指定模式

发布时间:2020-12-16 00:35:39 所属栏目:大数据 来源:网络整理
导读:例如把dir1和dir2两个目录下的所有.c和.h文件下的abc()函数替换成def()函数。下面的脚本会把改动前的文件存为以.old为后缀的文件。 ? #!/usr/bin/perl use strict; use warnings; use File::Find; sub process_source_file { ?my $in_filename = $_[0]; ?my

例如把dir1和dir2两个目录下的所有.c和.h文件下的abc()函数替换成def()函数。下面的脚本会把改动前的文件存为以.old为后缀的文件。

?

#!/usr/bin/perl

use strict;
use warnings;
use File::Find;

sub process_source_file {
?my $in_filename = $_[0];
?my $full_path = $_[1];
?my $out_filename = "cleanup_filename"; # a temp name
?print "source file ",$full_path,"n";
?open(my $in,"<",$in_filename) or die "Can't not open file $full_path: $!n";
?
?$/ = undef; ?# treat the whole file as a single string
?my $body = <$in>;
#?print $body;
?if (! ($body =~ /babcs*(/)) {? # unnecessary to proceed
??print "No specified pattern foundn";
??close $in or die "$in: $!n";
??return;
?}

?open(my $out,">",$out_filename) or die "Can't not open tmp file: $!n";

?$body =~ s/babcs*(/def(/g;

?print $out $body;

?close $in or die "$in: $!n";
?close $out or die "$out: $!n";
?rename($in_filename,"$in_filename.old");
?rename($out_filename,$in_filename);
}

sub process_file {
?# $File::Find::dir is the current directory name
?# $_ is the current filename within that directory
?# $File::Find::name is the complete pathname to the file

#?print "processing ",$File::Find::name,"n";
?if (-d $_) {
#??print $File::Find::name," is a directoryn";?
?} else {
??if ($_ =~ /.[ch]$/i) {
???#print "$_ = ",$_,",File::Find::name = ","n";?
???process_source_file($_,$File::Find::name);
??}
??#print $File::Find::name," is a filen";
?}
}

my @DIRLIST = ("dir1","dir2"); find(&;process_file,@DIRLIST);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读