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

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";

相关内容

热门资讯

中证A500ETF摩根(560... 8月22日,截止午间收盘,中证A500ETF摩根(560530)涨1.19%,报1.106元,成交额...
A500ETF易方达(1593... 8月22日,截止午间收盘,A500ETF易方达(159361)涨1.28%,报1.104元,成交额1...
何小鹏斥资约2.5亿港元增持小... 每经记者|孙磊    每经编辑|裴健如 8月21日晚间,小鹏汽车发布公告称,公司联...
中证500ETF基金(1593... 8月22日,截止午间收盘,中证500ETF基金(159337)涨0.94%,报1.509元,成交额2...
中证A500ETF华安(159... 8月22日,截止午间收盘,中证A500ETF华安(159359)涨1.15%,报1.139元,成交额...
科创AIETF(588790)... 8月22日,截止午间收盘,科创AIETF(588790)涨4.83%,报0.760元,成交额6.98...
创业板50ETF嘉实(1593... 8月22日,截止午间收盘,创业板50ETF嘉实(159373)涨2.61%,报1.296元,成交额1...
港股异动丨航空股大幅走低 中国... 港股航空股大幅下跌,其中,中国国航跌近7%表现最弱,中国东方航空跌近5%,中国南方航空跌超3%,美兰...
电网设备ETF(159326)... 8月22日,截止午间收盘,电网设备ETF(159326)跌0.25%,报1.198元,成交额409....
红利ETF国企(530880)... 8月22日,截止午间收盘,红利ETF国企(530880)跌0.67%,报1.034元,成交额29.0...