Reputation: 577
I have a netflow information report in text file, and I want to export them to csv format, how do I do that in Perl? I am new to Perl, just start to learn it.
Here is the text file:
Duration Flags
10.10.10.1 10.10.11.11 51251 445 2019-03-05 11:59:29.008 29.156 ......
10.10.10.2 10.10.11.22 51234 123 2019-03-05 11:40:29.008 30.156 .A..SF
I want to export this to excel format as follows.
10.10.10.1,10.10.11.11,51251,445,2019-03-05 11:59:29.008,29.156,......
10.10.10.2,10.10.11.22,51234,123,2019-03-05 11:59:29.008,30.156,.A..SF
I have try to do as below,
use strict;
use warnings;
open my $fh, '<', 'file.txt';
open my $fo, '>', 'file.csv';
while (<$fh>) {
next if ($. == 1);
s/\b \b/,/g;
my $text = (join ',', (split /\s+/, $_))."\n";
print $fo $text;
}
but the results is every line of start will be add one more ',' ,as below,
,10.10.10.1,10.10.11.11,51251,445,2019-03-05 11:59:29.008,29.156,......
,10.10.10.2,10.10.11.22,51234,123,2019-03-05 11:59:29.008,30.156,.A..SF
This is what I wants and what's problem with my code ?
10.10.10.1,10.10.11.11,51251,445,2019-03-05 11:59:29.008,29.156,......
10.10.10.2,10.10.11.22,51234,123,2019-03-05 11:59:29.008,30.156,.A..SF
Anyway of doing this?? Thank you.
Upvotes: 1
Views: 103
Reputation: 540
May something like this work?
use strict;
use warnings;
open my $fh, '<', 'text.txt';
open my $fo, '>', 'text.csv';
while (<$fh>) {
s/^\s+//;
s/\b \b/_/g;
my $text = (join ',', (split /\s+/, $_))."\n";
print $fo $text;
}
Upvotes: 0
Reputation: 69244
There are several steps to this problem. Rather than just handing the answer to you, I'm going to talk you through the steps and point you at the documentation for some functions that will help you at each stage.
open()
function is used to open a file and attach that file to a filehandle which you can use to read data from the file.< ... >
) for that.split()
function for doing that.join()
.print()
.close()
.I've deliberately left one interesting corner of your problem unmentioned. Everyone needs one meaty problem to get their teeth into, right? :-)
Have a go at writing something based on this information and, if you have more questions, feel free to ask them here.
Upvotes: 5