【问题标题】:How to export text file to csv file using perl?如何使用 perl 将文本文件导出到 csv 文件?
【发布时间】:2013-11-24 19:39:25
【问题描述】:

我有一个文本文件中的系统库存信息报告,我想将它们导出为 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 来做到这一点?感谢您的帮助。

【问题讨论】:

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

标签: perl


【解决方案1】:
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

【讨论】:

    【解决方案2】:

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

    awk -F': +' -v OFS="\t" 'BEGIN {
        print "Hostname", "OS", "MemoryGB", "CPUcount", "DiskSpace", "Location"
    }
    /:/ {printf "%s%c", $2, ($1 == "Location") ? "\n" : "\t"}
    '
    

    【讨论】:

      猜你喜欢
      • 2015-07-28
      • 1970-01-01
      • 1970-01-01
      • 2011-03-16
      • 2021-02-28
      • 1970-01-01
      • 2020-05-25
      • 2023-03-27
      • 1970-01-01
      相关资源
      最近更新 更多