Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用perl将文本文件导出到csv文件?_Perl - Fatal编程技术网

如何使用perl将文本文件导出到csv文件?

如何使用perl将文本文件导出到csv文件?,perl,Perl,我有一个文本文件中的系统库存信息报告,我想将它们导出为csv格式,如何在Perl中实现这一点?我是Perl新手,刚开始学习 以下是文本文件: Hostname: computer1 OS: Windows 2008 Server MemoryGB: 4 CPUcount: 2 DiskSpace:80GB Location: Cube1 Hostname: computer2 OS: Windows 2012 Server MemoryGB: 8 CPUcount: 2

我有一个文本文件中的系统库存信息报告,我想将它们导出为csv格式,如何在Perl中实现这一点?我是Perl新手,刚开始学习

以下是文本文件:

Hostname: computer1
OS:       Windows 2008 Server
MemoryGB: 4
CPUcount: 2
DiskSpace:80GB
Location: Cube1

Hostname: computer2
OS:       Windows 2012 Server
MemoryGB: 8
CPUcount: 2
DiskSpace:100GB
Location: Cube2
我希望将它们导出到CSV文件中,如下所示:

Hostname    OS                     MemoryGB    CPUcount    DiskSpace    Location
Computer1   Windows Server 2008       4           2           80GB       Cube1
Computer2   Windows Server 2012       8           2           100GB      Cube2

我如何使用Perl来实现它?感谢您的帮助。

如果字段顺序一致,您可以使用以下awk:

open ($fh, '<', $inputfile) || die "error reading $inputfile";
while(<$fh>) {
  chomp;
  $line = $_;
  $line =~ s/\s+/ /; # cleanup spaces
  $line =~ s/.*: //; # get rid of headers
  push (@lines, $line);
}
close($fh);

$string = join (",", @lines);
$string =~ s/,,/\n/;
# string has the output, without header
awk -F': +' -v OFS="\t" 'BEGIN {
    print "Hostname", "OS", "MemoryGB", "CPUcount", "DiskSpace", "Location"
}
/:/ {printf "%s%c", $2, ($1 == "Location") ? "\n" : "\t"}
'

我为您解决了格式问题。请不要再次还原更改。嗨,TLP。第一次来这里,我想把格式弄好,但弄糟了。谢谢。首先,你需要打开文件以便逐行阅读和扫描。然后根据冒号前的字符串生成一个字段字典。您的记录似乎用空行分隔。您可以使用段落模式读取它们,将输入记录分隔符设置为空字符串$/=。然后你可以在换行符上拆分,在冒号上拆分以分离各个值。你可以发布你尝试过的内容吗?