我在文本文件中有一个系统库存信息报告,我想将它们导出为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执行此操作?谢谢你的帮助。
答案 0 :(得分:0)
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
答案 1 :(得分:0)
如果字段的顺序一致,您可以使用以下awk:
awk -F': +' -v OFS="\t" 'BEGIN {
print "Hostname", "OS", "MemoryGB", "CPUcount", "DiskSpace", "Location"
}
/:/ {printf "%s%c", $2, ($1 == "Location") ? "\n" : "\t"}
'