• 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
    ";
                        }
                    }
                }
    
            }
        }
    }
    
    scan_file($path);
    

    执行

    λ perl main.pl "./test/*" ".txt .html .js" ajanuw/world
    ./test/ajanuw.txt
    ./test/dist/bundle.html
    ./test/src/index.js
    
  • 相关阅读:
    python—虚拟环境搭建
    pytnon—线程,进程
    python——新excel模块之openpyxl
    装饰器——应用
    css样式
    HTML
    广图登陆知网下载资源教程
    使用k-近邻算法改进约会网站的配对效果
    k-近邻算法概述
    机器学习基础
  • 原文地址:https://www.cnblogs.com/ajanuw/p/9275767.html
Copyright © 2020-2023  润新知