CSV文件格式

时间:2011-03-28 20:43:45

标签: perl parsing csv

我编写了一个perl脚本来输出一个文本文件,其中包含我扫描到microsoft excel中的ip地址和端口。现在数据在Excel中,我的老板要我用csv格式组织文件,例如

Server, port, protocol, random, random, random
ns1,    25,   tcp,      stuff,  stuff,  stuff

任何人都可以帮我这个吗?

代码:

#!/usr/bin/perl

$input = `Cat /cygdrive/c/Windows/System32/test11.txt | grep -v 'SYN Stealth'`;
chomp input;
$output =" /cygdrive/c/Users/bpaul/Desktop/194.csv ";
if (! -e "$output")
{
`touch $output`;
}
open (OUTPUTFILE, ">$output") || die "Can't Open file $output";
print OUTPUTFILE "$input\n";
close (OUTPUTFILE);

这是我文件的一部分

Nmap scan report for 69.25.194.2 Host is up (0.072s latency). Not shown: 9992 filtered ports PORT STATE SERVICE 25/tcp open smtp
80/tcp open http
82/tcp open xfer
443/tcp open
https 4443/tcp closed
pharos 5666/tcp closed
nrpe 8080/tcp closed
http-proxy 9443/tcp closed tungsten-https

到目前为止,我的代码使用了我的txt文件并将其输出到excel现在我需要格式化这样的数据:

期望的输出:

Server, port, protocol, random, random, random
ns1,    25,   tcp,      stuff,  stuff,  stuff

1 个答案:

答案 0 :(得分:4)

当你说69.25.194.2时,我假设你的意思是ns1

use strict;
use warnings;

use Text::CSV_XS qw( );

my $csv = Text::CSV_XS->new({ binary => 1, eol => "\n" });

$csv->print(\*STDOUT, [qw(
    Server
    port
    protocol
    random
    random
    random
)]);

my $host = '[unknown]';

while (<>) {
    $host = $1 if /Nmap scan report for (\S+)/;

    my ($port, $protocol) = m{(\d+)/(\w+) (?:open|closed)/
        or next;

    $csv->print(\*STDOUT, [
        $host,
        $port,
        $protocol,
        'stuff',
        'stuff',
        'stuff',
    ]);
}

用法:

grep -v 'SYN Stealth' /cygdrive/c/Windows/System32/test11.txt | perl to_csv.pl > /cygdrive/c/Users/bpaul/Desktop/194.csv

Text::CSV_XS

更新:将硬编码的ns1替换为已扫描计算机的地址。

更新:将通用用法替换为OP将使用的内容。