perl从文件中搜索关键字

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老帽爬新坡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值