CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Need a Custom or Prewritten Perl Program?: I need a program that...:
parse file

 



q18
New User

Feb 12, 2013, 7:37 AM

Post #1 of 2 (3022 views)
parse file Can't Post

I have text:

Quote
date=2013-01-02 time=23:59:59 devname=fg-abc device_id=FG3434 log_id=0038000007 type=traffic subtype=other pri=warning vd=root src=1.1.1.1 src_port=52752 src_int="interf" dst=2.2.2.2 dst_port=80 dst_int=unknown-0 SN=0 status=deny policyid=0 dst_country="Italy" src_country="Italy" service=HTTP proto=6 duration=0 sent=0 rcvd=0 msg="no session matched"

I want write to my DB(mysql row ) only informations like:
date=2013-01-02 time=23:59:59 type=traffic src=1.1.1.1 src_port=52752 src_int="interf" dst=2.2.2.2 dst_port=80

Other data must be ignore.
Sometimes the text will be different but always includes date,time,type,src_port,src_int,dst,dst_port
At the moment I have:

Code
open (FILE ,"log.old"); 
while (<FILE>) {
chomp ();
my %zxc = split (/\b[= ]\b/);
foreach my $k (keys %zxc) {
print "$k: $zxc{$k}\n";
}}
close (FILE);

OUTPUT:

status: deny
time: 23:59:59
date: 2013-01-02
log_id: 0038000007
policyid: 0
subtype: other
dst_country="Italy" src_country="Italy" service: HTTP
sent: 0
pri: warning
src_int="interf" dst: 2.2.2.2
dst_int: unknown-0
proto: 6
src_port: 52752
rcvd: 0
devname: fg-abc
src: 1.1.1.1
duration: 0
dst_port: 80
device_id: FG3434
SN: 0
msg="no: session
vd: root
type: traffic


gut the problem is with text in ""
How can I parse this text ?


(This post was edited by q18 on Feb 12, 2013, 3:00 PM)


BillKSmith
Veteran

Feb 14, 2013, 1:15 PM

Post #2 of 2 (2988 views)
Re: [q18] parse file [In reply to] Can't Post

Use the module Text::CSV_XS to parse your file.

Code
use strict; 
use warnings;
use Text::CSV_XS;
use Data::Dumper qw(Dumper);
my $options = {
quote_char => q("),
sep_char => q( ),
allow_loose_quotes => 1,
};
my %zxc;
my $csv = Text::CSV_XS->new($options)
or die "Cannot use CSV: ".Text::CSV_XS->error_diag ();
open my $CSV_FILE, '<', 'q18.csv' or die "Cannot open CSV file:$!";
while ( my $row = $csv->getline($CSV_FILE)){
for (@$row) {
my ($key, $value) = split '=';
$zxc{$key} = $value;
}
}
print Dumper \%zxc;

Good Luck,
Bill

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives