【问题标题】:Replace commas in csv file替换csv文件中的逗号
【发布时间】:2011-02-26 20:49:50
【问题描述】:

我正在使用 perl 将原始数据库转储解析为 csv 文件。问题是它的格式不适合 Excel。我需要在文件顶部添加一个标题,并删除所有逗号。这可以在 perl 单行中完成,但这是更大的 perl 脚本的一部分,所以我想在主 perl 脚本中完成。我正在尝试这样的事情:

    print "Formatting csv file... $csvFile\n";

    open IN, '<', $csvFile or die;
    my @contents = <IN>;
    close IN;

    @contents =~ s/\'//g;

    open OUT, '>', $csvFile or die;
    print OUT @contents;
    close OUT;

你当然可以这样做:

    @contents =~ s/\'//g;

我需要删除逗号并在文件顶部添加一行。有什么想法吗?

【问题讨论】:

  • s/\'//g 如何删除所有逗号?这将删除所有单引号。
  • 使用字段分隔符,而不是逗号,例如“|” ,从您的数据库中转储时可能是另一种解决方案。如果数据字段中嵌入逗号,您的正则表达式可能会导致问题,例如奥莱利。导入 Excel 时,您可以指定字段分隔符。

标签: perl


【解决方案1】:

逐行读取文件并输出到一个新的临时文件,然后将该文件重命名回原来的文件更容易:

print "Formatting csv file... $csvFile\n";
my $newfile = '/tmp/newfilename.csv';
open(my $inFileHandle, '<', $csvFile) or die "cannot open $csvFile for reading: $!";
open(my $outFileHandle, '>', $newFile) or die "cannot open $newFile for writing: $!";

print $outFileHandle "The header line you need to add\n";
while (my $line = <$inFileHandle>)
{
    $line =~ s/\'//g;
    print $outFileHandle $line;
}

close $inFileHandle;
close $outFileHandle;
rename $newFile, $csvFile;

...但我想知道您所说的“Excel 的格式不正确”是什么意思,以及为什么您觉得需要删除所有单引号。

【讨论】:

    【解决方案2】:

    标题部分就快到了。

    对于输出的第一行,只需将其打印到 CSV 之前的文件中:

    my $header='"field 1","field 2","field n"';
    
    open OUT, '>', $csvFile or die;
    print OUT "$header\n";
    # print the CSV part...
    close OUT;
    

    对于 CSV 部分,请使用库。有许多。 This tutorial 会告诉你。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多