开发者

perl regx , pick word after the word connect

开发者 https://www.devze.com 2023-02-19 14:41 出处:网络
This is my log connect called menu transfer disconnect connect called transfer disconnect i want to pick the word, when the word exactly next to ,

This is my log

connect
called
menu
transfer
disconnect
connect
called
transfer
disconnect

i want to pick the word, when the word exactly next to , When the word like

connect

menu transfer disconnect means,

i should pick the word transfer,

if my flow like

connect called transfer disconnect

开发者_开发问答

then i dont want to pick the word transfer,


You coud try something like:

Updated to standard Perl distribution :

#!/usr/bin/perl
use strict;
use warnings;

my $count = 0;
while(<DATA>) {
    chomp;
    $count = 1 if $_ eq 'connect';
    if ($count == 3) {
        print "2 words after is : $_\n";
        $count = 0;
    }
    $count++ if $count;
}


__DATA__
connect
called
menu
transfer
disconnect
connect
called
transfer
disconnect

output:

2 words after is : menu
2 words after is : transfer


Using a regex to solve this will assume that you have your log file in a single variable. Provided that your log file is not very large you can do this as follows:

use File::Slurp qw(slurp);
my $log = slurp('path/to/logfile');

Or if you prefer not to use a non-standard Perl module for this:

{
  local $/;
  open my $fh, '<', 'path/to/logfile' or die $!;
  my $log = <$fh>;
  close $fh;
}

To get the instances where the word after transfer matches 'connect' but only where the flow is menu -> transfer -> ... you can do the following:

while ( $log =~ m{menu\s+transfer\s+(\w*connect\w*)}g ) {
    print "transfer -> $1\n";
}


Why would you use Regex? It is not a good use case. Just

while (<>) { chomp; last if ($_ eq 'connect'); }
$_ = <>;
print;

would do.

0

精彩评论

暂无评论...
验证码 换一张
取 消