[Ilugc] Help needed in ruby

  • From: lug@xxxxxxxxxxxxxxxxxx (Chandrashekar Babu)
  • Date: Wed Sep 1 20:22:38 2010

Dear Ranjith,

Hi all,
 The function of this script is used to print the
 aleurier_access.log (apache log file) file content exactly.

[snip]

What i like to do is
How to print individual set values?
for eg,
If I want to print the %h (remote host id) set values alone?
I want to sort %h set values?
Repeated host id to printed only once and also other unique host
ids values and store %h values in a database?

I don't know if I understood your requirement/query correctly.
Assuming that you want to parse access_log file such that for every
host entry in the access_log, you want to group corresponding fields
together as a set of records, the code could be something like
below:

# --------------8<---------------------------------8<---------------
require 'rubygems'
require 'apachelogregex'
require 'pp'

format = '%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"'
parser = ApacheLogRegex.new(format)
access_log = Hash.new
# Creating a hash of an array of hashes!
# Can be simplified based on your actual requirement.

File.readlines('aleurier_access.log').collect do |line|
  record = parser.parse(line)
  # The code below does the actual job. Can be a one-liner
  # if you know ternary operators or maybe if expression.
  if access_log.key? record["%h"]
     access_log[record["%h"]] << record
  else
     access_log[record["%h"]] = Array.new
  end
end

# Now let's test some!
puts access_log.keys
while true
    print "Enter ip address: "
    ipaddr = gets.chomp
    puts "-" * 40
    pp access_log[ipaddr]
    puts "-" * 40
end
# --------------8<---------------------------------8<---------------

Is this what you wanted ?

--
Chandrashekar Babu.,
http://www.chandrashekar.info/
http://www.slashprog..com/

Other related posts: