29. Perl 脚本实战-confview

    xiaoxiao2022-07-04  194

    confview 命令用于查看配置文件中有效配置信息,以#开头的行或空行会被认为是有效信息. 主要特性:

    自动过滤空行和注释支持高亮显示关键字有效信息保留原行号

    1. 用法示例

    1.1 查看配置文件有效配置信息

    $ confview redis.conf.7481 [2 ] include /usr/local/etc/redis/redis.conf [7 ] bind 127.0.0.1 [10] protected-mode no [13] port 7481

    1.2 查看配置文件有效配置信息, 并高亮显示关键字

    终端执行时, bind 和 port 关键字会高亮显示

    $ confview redis.conf.7481 bind port [2 ] include /usr/local/etc/redis/redis.conf [7 ] bind 127.0.0.1 [10] protected-mode no [13] port 7481

    1.3 显示配置完整信息, 不过滤空行和注释行

    $ confview -a redis.conf.7481 [1 ] # 引入原配置 [2 ] include /usr/local/etc/redis/redis.conf [3 ] [4 ] ######################################## 自定义配置 ######################################## [5 ] [6 ] # 修改绑定ip [7 ] bind 127.0.0.1 [8 ] [9 ] # 设置关闭保护模式 [10] protected-mode no [11] [12] # 设置端口号为7481 [13] port 7481

    2. 命令源码

    #!/usr/bin/perl #Desc 查看配置文件 #Auth zonggf #Date 2016-12-30 use warnings; use Term::ANSIColor qw(:constants); $Term::ANSIColor::AUTORESET = 1; #检查是否是查询帮助 sub check_help{ my $param = $ARGV[0]; $show_all = 0; if("-h" eq $param || "--help" eq $param){ print BOLD BLUE "Desc: "; print "查看配置文件内容,并高亮显示筛选字符串, 默认过滤注释行和空行,可添加-a 显示文件所有内容\n"; print BOLD BLUE "Args: "; print "参数1: 配置文件 其它参数: 需要高亮显示的关键字\n"; print BOLD BLUE "Exam: "; print "viewcfg redis.conf port client\n"; print BOLD BLUE "Auth: "; print "zonggf\n"; print BOLD BLUE "Date: "; print "2016-12-30\n"; exit; }elsif ("-a" eq $param){ $show_all = 1; shift @ARGV; } } #desc 输出有颜色的字符串 #para1 接收至少两个参数以上,第一个参数为要格式化的字符串,之后的参数为要使用颜色的字符串 sub print_color(){ # 如果长度小于2, 那么不进行格式化输出,直接打印 if(@_ < 2){ print shift @_; return; } #获取要格式化颜色的字符串 my $line = shift @_; #获取要高亮的字符串数组 my @patterns = @_; #获取要高亮显示的字符串数组,拼接正则模式 my $spectors = (shift @_) . '+'; foreach(@_){ $spectors .= "|$_+"; } #按正则模式进行分组 my @arrays = split(/($spectors)/, $line); #输出结果 for my $item(@arrays){ #直接使用@patterns 数组反向匹配,数组内插时,每个字符串直接会有空格 my $pattern = "@patterns"; #字符串中查找元素,如果有的话则高亮显示,否则正常显示 my $idx = index($pattern, $item); if($idx > -1){ print BOLD RED $item; }else{ print $item; } } } #格式化索引长度 #参数: 接收两个参数 # para1: 需要格式化的索引 # para2: 数组长度 #返回: [1 ] sub fmt_idx{ return shift @_ if @_ < 2; my ($str, $array_length) = @_; my $length = length $array_length; return sprintf "[%-${length}s] ", $str; } #################### 主程序 #################### #校验帮助 &check_help; #配置文件名称 $file_name = shift @ARGV; #读取文件内容,获取文件行数 open $f_cfg, "<", $file_name or die "[错误] $file_name not exists !!\n"; @lines = <$f_cfg>; $lines_length = @lines; #遍历文件内容 for $idx (1 .. @lines){ $line = $lines[$idx-1]; #如果是空行或者注释行 if($line =~ /^$|^#/){ if($show_all == 1){ print BOLD GREEN &fmt_idx($idx,$lines_length); &print_color($line ,@ARGV); } }else{ print BOLD GREEN &fmt_idx($idx,$lines_length); &print_color($line ,@ARGV); #记录总行数 $rs_cnt++; } } #打印配置文件总行数 print BOLD CYAN "\nEffective Lines: $rs_cnt; Total Lines: $lines_length\n"; #关闭文件流 close $f_cfg;
    最新回复(0)