LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Select a text between 2 strings (Perl) (https://www.linuxquestions.org/questions/programming-9/select-a-text-between-2-strings-perl-911570/)

haux 11-02-2011 07:47 PM

Select a text between 2 strings (Perl)
 
I wanna select just two values from our web server's log.

The log looks like this :


100.200.200.100 - - [15/Mar/2011:12:01:09 -0400] "GET /mediaencoder.php?logins=MYMP3;J5J5J5;0%7CCFWMFM;Q5Q5Q5;2%C8;1&version=1.1&meversion=1.3.0 HTTP/1.1" 200 8751 "-" "-" 163 8912

I want to select the words between "logins=" and ";" (MYMP3 in the exemple line). I tried this :


$file="/files.txt";
open(SESAME, $file);
while(<SESAME>)
{
my($line) = $_;

if ($line =~ /\blogins=\b(.*?)\b';'\b/) {
$result = $1;
# do something with results
print "RESULT= $result\n";
}
}

close (SESAME);



But I get an empty value for $RESULT. Do you have any idea why it doesn' t work ?

Cedrik 11-02-2011 08:18 PM

You want to match a word in the example, so need only 2 \b, one before and one after the word
Code:

if (/logins=\b(.*?);\b/) {
This also works :
Code:

if (/logins=(.*?);/)

haux 11-03-2011 07:58 AM

Great! thank you Cedrik it works :-)

I want also to select the IP (the first column in each line) I am trying this but it doesn't work :

if ($line =~ /^\b(\d+\.\d+\.\d+\.\d+)\b\s/) {
$IP_SOURCE = $1;
print "RESULT= $result $IPSOURCE\n";
}




I don't understand where is the problem !

Thx

Cedrik 11-03-2011 08:19 AM

Keep it simple...
Code:

if(/^(\d+\.\d+\.\d+\.\d+)/) {
[edit]
To grep both IP and logins values, you may try:

Code:

while(<SESAME>)
    my ($ip, $login) = (/^(\d+\.\d+\.\d+\.\d+).+logins=(.*?);.*/);
    print "IP: $ip LOGIN: $login\n";
}


haux 11-03-2011 08:58 AM

Great thank you !


All times are GMT -5. The time now is 08:36 PM.