perl从文件中搜索关键字
创始人
2024-04-11 17:16:13

1,perl从文件中搜索包含关键字的行。

#!/usr/bin/perl

use strict;
use warnings;

my $log_file = '/home/aaa/log';

open(LOG,"< $log_file") or die "Unable to open logfile:$!\n";
while(){
    print  if /\[error]|error/;
}

close(LOG);

解释:从文件中打印包含“[error]”或者“error‘关键字的行。


2,perl从文件中找出要匹配的关键字

#!/usr/bin/perl

use strict;
use warnings;

if (scalar(@ARGV) < 2) {
    print "Usage: $0 \n\n";
    exit(1);
}

my $ip = $ARGV[0];
my $iface = $ARGV[1];

# Check if ip is already here
my $ip_check = `/sbin/ip addr show`;
if ($ip_check  =~ /$ip/) {
    print "OK: IP address is already here\n";
    exit(0);
}

# Get physics device
my $ipaddr = `/sbin/ifconfig $iface`;

# Get ethernet address
$ipaddr =~ /HWaddr\s*([0-9A-F\:]+)/i;
my $if_eth = $1;
print "$if_eth\n";

# Get broadcast address and netmask
$ipaddr =~ /Bcast:\s*([\d\.]+)\s*Mask:\s*([\d\.]+)/i;
my $if_bcast = $1;
my $if_mask = $2;

print "$if_bcast\n";
print "$if_mask\n";

print "OK\n";
exit(0);

脚本运行如下:
[root@localhost crontab]# ./find_ip.pl 192.168.1.91 eth0
00:0C:29:7D:EB:12
192.168.1.255
255.255.255.0
OK


3,输出文件的前几行

#!/usr/bin/perl

use strict;
use warnings;

my $filename = '/opt/1.txt';
open FH, "< $filename" or die "can't open $filename  ..... ($!)";

my $line = 0;
my %file = map {($line++, $_)} ;

print $file{0};
print $file{1};


4,输出文件前几行的另外一种方法

#!/usr/bin/perl

use strict;
use warnings;

my $filename = '/opt/1.txt';

tie my @array, 'Tie::File', $filename or die "$!";

my $total = substr($array[0], 0, length($array[0])-1);
my $use   = (split(' ', $array[1]))[0];
my $mail_count   = (split(' ', $array[1]))[1];

print "$total\n";
print "$use\n";
print "$mail_count\n";

相关内容

热门资讯

玩家必看教程!智星德州扑克辅助... 玩家必看教程!智星德州扑克辅助挂多功能透视工具,好像真的是有挂(有挂详细)1、该软件可以轻松地帮助玩...
记者揭秘!wpk辅助挂多功能透... 记者揭秘!wpk辅助挂多功能透视工具,原来存在有挂(有挂猫腻)1、全新机制【wpkai辅助工具激活码...
科普!德扑圈辅助挂多功能透视工... 科普!德扑圈辅助挂多功能透视工具,总是有挂(有挂教学)1、实时德扑圈透视辅助更新:用户可以随时随地访...
玩家必备攻略!WPK辅助挂多功... 玩家必备攻略!WPK辅助挂多功能透视工具,其实存在有挂(确实有挂)1、任何WPK透视是真的假的的玩家...
分享一款!智星菠萝德州辅助挂多... 分享一款!智星菠萝德州辅助挂多功能透视工具,总是是真的有挂(有挂神器)1)智星菠萝德州辅助插件:进一...