script_kiddie
script_kiddie

Reputation: 1187

extracting http response code from log

Apache log file entry

64.242.88.10 - - [07/Mar/2004:20:11:33 -0800] "GET /twiki/bin/attach/TWiki/TWikiSite HTTP/1.1" 401 12846

Using regex I want to extract the HTTP response code

=~ /HTTP/1.1"\s(response_code)\s/
print $response_code

I can do such thing in Python or Ruby but don't know if and how can I do it in Perl.

Just extracting a particular value without using multiple split operations.

I just want to scan a line in a file, and print http_response_code placed at /HTTP/1.1"\s(response_code)\s/

Upvotes: 0

Views: 1985

Answers (3)

A human being
A human being

Reputation: 1220

Yes, you can do this in perl, this is the code:

#!/usr/bin/env perl 

use strict;
use warnings;

open FILE, "test.txt" or die $!;
while( my $string = <FILE> )
{
    if( $string =~ /HTTP\/1.1"\s(\d+)/ )
    {
    print "$1\n";
    }
}

output:

$ perl testRegex.pl 
401 

Upvotes: 2

Borodin
Borodin

Reputation: 126722

A regex is unnecessary here. split is faster and more convenient.

my $line = '64.242.88.10 - - [07/Mar/2004:20:11:33 -0800] "GET /twiki/bin/attach/TWiki/TWikiSite HTTP/1.1" 401 12846';

my $response_code = (split ' ', $line)[-2];
print $response_code;

output

401

Upvotes: 0

Miguel Prz
Miguel Prz

Reputation: 13792

This works for me:

use strict;
use warnings;

my $line = qq!64.242.88.10 - - [07/Mar/2004:20:11:33 -0800] "GET /twiki/bin/attach/TWiki/TWikiSite HTTP/1.1" 401 12846!;

if( $line =~ m!HTTP/1.1" +(\d+)! ) {
    print $1, "\n";  # <--- prints: 401
}

Upvotes: 0

Related Questions