【发布时间】:2011-10-11 21:31:39
【问题描述】:
我有几个大的 CSV 文件,我需要使用 1 到多个参数进行搜索,如果我找到一个匹配项,我需要将该行保存在另一个文件中。下面是一个成功运行但对 5gb 文件非常慢的 perl 代码示例。任何关于加快速度的建议将不胜感激。
#!/usr/bin/env perl
use Text::CSV_XS;
$numArgs = $#ARGV;
#First Parameter is the input file name
$Finput = $ARGV[0];
chomp($Finput);
#Second Parameter is the output file name
$Foutput = $ARGV[1];
chomp($Foutput);
# Open the Control file but quit if it doesn't exist
open(INPUT1, $Finput) or die "The Input File $Finput could not be found.\n";
open(OUTPUT1, ">$Foutput") or die "Cannot open output $Foutout file.\n";
my $csv = Text::CSV_XS->new();
open my $FH, "<", $Finput;
while (<$FH>) {
$csv->parse($_);
my @fields = $csv->fields;
if ($fields[0] == 10000) {
if ($fields[34] eq 'abcdef') {
if ($fields[103] == 9999) {
print OUTPUT1 "$_\n";
}
}
}
}
【问题讨论】:
-
if( $fields[0] = 10000)... 和if( $fields[34] = 'abcdef' )可能没有按照你的想法做。您可能需要==运算符(用于数字比较)和eq运算符用于字符串比较。很难想象这段代码实际上按照发布的方式正确运行。 -
您也永远不会在示例代码中阅读
INPUT1。为了获得真正准确的答案,我们需要知道您现有的(工作)算法是什么样的,或者您的输入和输出数据应该是什么样的。由于发布的代码不能准确表示您实际成功但运行缓慢,因此我们只能猜测您真正需要什么。 -
感谢 DavidO...我更正了运算符,并且在调用此脚本时确实接受了 2 个参数,所以我像这样运行它...perl script.pl
-
继续思考...所以我像这样运行它...perl script.pl input_file.csv out_putfile.csv...这确实读入第一个文件并循环通过它并产生第二个如果找到文件。输入日期是这样的..(20110718043719,10000,"NAME, Association",1110101,,I,1,1,USA,USA......新行然后是另一行 20110718043719,10000,"NAME, Association" ,1110101,,I,1,1,USA,USA)。如果找到匹配项,我们应该将整行复制到新文件中。