我有一个文本文件形式的系统清单信息报告,我想将它们导出为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来完成这项工作?谢谢你的帮助。
发布于 2013-11-25 08:28:27
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发布于 2013-11-25 13:05:03
如果字段的顺序是一致的,您可以使用以下awk:
awk -F': +' -v OFS="\t" 'BEGIN {
print "Hostname", "OS", "MemoryGB", "CPUcount", "DiskSpace", "Location"
}
/:/ {printf "%s%c", $2, ($1 == "Location") ? "\n" : "\t"}
'https://stackoverflow.com/questions/20179983
复制相似问题