coolent
coolent

Reputation: 21

perl regex multiple words in a line

I am trying to split these values , I am not getting as expected

$line = "sep 11 14:06:18 github-01-com sshd[4609]: Received disconnect from 192.168.1.1: disconnected by user";

if($line =~ /^(.*)\s+(\w+)/){
print "$1\n$2\n";

I am trying to get output like these

$val1 = "sep 11 14:06:18";
$val2 = "github-01-com";
$val3 = "sshd[4609]:"
$val4 = "Received disconnect from 192.168.1.1: disconnected by user"

thanks

Upvotes: 1

Views: 49

Answers (1)

Lee Duhem
Lee Duhem

Reputation: 15121

For this specific line, you can decode it like this:

#!/usr/bin/perl

use strict;
use warnings;

my $line = "sep 11 14:06:18 github-01-com sshd[4609]: Received disconnect from 192.168.1.1: disconnected by user";

if ($line =~ m/^(\w+\s+\d+\s+(?:\d|:)+)\s+([^\s]+)\s+([^\s]+)\s+(.*)$/) {
    print "\$1 = $1\n\$2 = $2\n\$3 = $3\n\$4 = $4\n";
}

Here is the output:

$1 = sep 11 14:06:18
$2 = github-01-com
$3 = sshd[4609]:
$4 = Received disconnect from 192.168.1.1: disconnected by user

By the way, depends on which kind of log file you are trying to parse, there may be exist some modules to do it, try to search them in CPAN.

Upvotes: 2

Related Questions