#!/usr/bin/perl
use strict;
my @a_rec;
my @a_out;
my $i;
my $line;
my $outline;
my $col1;
my $infile = "monitor.dat";
my $outfile = "monitor.csv";
open INFILE, "<$infile"
or die "can't open file: $!";
open OUTFILE, ">$outfile"
or die "can't open file: $!";
print OUTFILE "MONITOR,DESCRIPTION,MAXTHRESHOLD,SEVERITY\n";
@a_rec = (<INFILE>);
$i=0;
while (@a_rec[$i] )
{
chomp($a_rec[$i]);
while ( $a_rec[$i] )
{
$line = $a_rec[$i];
$col1 = (split(/ /, $line)) [0];
$line =~ s/$col1\s*//;
push (@a_out, $line);
$i++;
chomp ($a_rec[$i]);
}
if ( $a_out[0] )
{
$outline = join(",", @a_out);
print OUTFILE "$outline\n";
}
undef @a_out;
$i++;
}
close(INFILE);
output:
cat monitor.csv
MONITOR,DESCRIPTION,MAXTHRESHOLD,SEVERITY
"ALERT_INFO","Triggered when informational Netware alert occured",95,Normal
"ALERT_MAJOR","Triggered when major Netware alert occured",,Major
I got lazy yesterday and just printed the four column headers. I changed the code to to dynamically determine the column headers. This will allow you to add more rows to your monitor logs and they will be picked up automatically or to use the code against other files with the same format.
If I add rows to the monitor.dat file:
MONITOR "ALERT_INFO"
DESCRIPTION "Triggered when informational Netware alert occured"
MAXTHRESHOLD 95
SEVERITY Normal
NEW_COL NEW_VAL_1
MONITOR "ALERT_MAJOR"
DESCRIPTION "Triggered when major Netware alert occured"
MAXTHRESHOLD
SEVERITY Major
NEW_COL NEW_VAL_2
They get picked up automatically:
MONITOR,DESCRIPTION,MAXTHRESHOLD,SEVERITY,NEW_COL
"ALERT_INFO","Triggered when informational Netware alert occured",95,Normal,NEW_VAL_1
"ALERT_MAJOR","Triggered when major Netware alert occured",,Major,NEW_VAL_2
The new code:
#!/usr/bin/perl
use strict;
my @a_rec;
my @a_out;
my @a_hdr;
my $col_hdr = 0;
my $i;
my $line;
my $outline;
my $col1;
my $infile = "monitor.dat";
my $outfile = "monitor.csv";
open INFILE, "<$infile"
or die "can't open file: $!";
open OUTFILE, ">$outfile"
or die "can't open file: $!";
@a_rec = (<INFILE>);
$i=0;
while (@a_rec[$i] )
{
chomp($a_rec[$i]);
while ( $a_rec[$i] )
{
$line = $a_rec[$i];
$col1 = (split(/ /, $line)) [0];
unless ( $col_hdr )
{
push (@a_hdr, $col1);
}
$line =~ s/$col1\s*//;
push (@a_out, $line);
$i++;
chomp ($a_rec[$i]);
}
unless ( $col_hdr )
{
$outline = join(",", @a_hdr);
print OUTFILE "$outline\n";
$col_hdr++;
}
if ( $a_out[0] )
{
$outline = join(",", @a_out);
print OUTFILE "$outline\n";
}
undef @a_out;
$i++;
}
close(INFILE);
close(OUTFILE);