码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-07-06 23:31:39      阅读:314      评论:0      收藏:0      [点我收藏+]

标签:执行   int   文件名   undle   err   for   code   scan   替换   

不会读取 影藏文件

main

#!/usr/bin/perl
my ($path, $rp) = @ARGV;

sub search_file{
    my ($fname, $rp) = @_; # 获取操作文件名 和 查询的正则
    my ($o) = split("/", $rp);
    open(of, "<$fname") or die "$fname 文件打开失败!$!";
    while(<of>){
        chomp;
        if($_ =~ /$o/){
            print "$fname\n";
            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") or die "$fname 文件打开失败!$!";
    while(<of>){
        chomp;
        $_ =~ s/$o/$n/;
        push @data, "$_\n";
    }

    chomp @data; # 砍掉最后的 \n
    open(wf, "+>$fname") or die "Error: 文件$nfname打开失败$!";
    print wf @data;
    return 1;
}

my @change_files = (); # 受到影响的文件

sub scan_file{
    my @files = glob(@_[0]);
    foreach (@files){
        if(-d $_){
            my $path = "$_/*";
            scan_file($path);
        }elsif(-f $_){
            if( change_file($_, $rp) ){
                push @change_files, $_;
            }
        }
    }
}

scan_file($path);

执行

读取文本, world替换为ajanwu

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

读取指定类型文件

修改下 scan_file 函数

my $path = "./test/*";
my @suffix_names = qw[.css .html];

sub scan_file{
    my @files = glob(@_[0]);
    foreach (@files){
        if(-d $_){
            my $path = "$_/*";
            scan_file($path);
        }elsif(-f $_){
           my $fname = $_;
           foreach (@suffix_names){
               if($fname =~ m/$_$/){
                   print "$fname\n";
               }
           }
        }
    }
}

scan_file($path);

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

标签:执行   int   文件名   undle   err   for   code   scan   替换   

原文地址:https://www.cnblogs.com/ajanuw/p/9275767.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!