• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

不会读取 影藏文件

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

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Perl读写Excel简单操作发布时间:2022-07-22
下一篇:
perl读取文件发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap