PERL脚本比较3个CSV文件&创建一个新的CSV文件

时间:2014-10-15 05:11:59

标签: perl shell csv compare

我正在努力比较3个csv文件并使用新输出创建另一个csv文件。

文件1

  Name,Color,Food,Point
  David,Orange,Pasta,12.34
  Raver,Blue,Pizza,13.35
  John,Red,Noodles,14.36
  Armond,Black,Sandwich,15.37

文件2

Name,Task
David,Success
Raver,Success
John,Success
Armond,Failure

文件3

Color,Stock
Orange,Available
Blue,Available
Red,OutOfStock
Black,Available

输出文件

Name,Color,Food,Point,Task,Stock
David,Orange,Pasta,12.34,Success,Available
Raver,Blue,Pizza,13.35,Success,Available
John,Red,Noodles,14.36,Success,OutOfStock
Armond,Black,Sandwich,15.37,Failure,Available

请帮助我。提前谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用2 join s:

join -t, -j 1 file1 file2 | join -t, -1 2 -2 1 -o 1.1,1.2,1.3,1.4,1.5,2.2 - file3

说明:

  • join -t, -j 1 file1 file2:加入第1个字段的前两个文件。
  • join -t, -1 2 -2 1 ... - file3:前一个语句现在代表第一个文件(-)。这与第3个文件一起使用。
  • -o 1.1,1.2,1.3,1.4,1.5,2.2:您的示例中的输出顺序。

答案 1 :(得分:0)

我在这里尝试了一些东西。

<强>输出

Name,Color,Food,Point,Task,Stock
David,Orange,Pasta,12.34,Success,Available
Raver,Blue,Pizza,13.35,Success,Available
John,Red,Noodles,14.36,Success,OutOfStock
Armond,Black,Sandwich,15.37,Failure,Available

这有效!

#! /ms/dist/perl5/bin/perl5.10
use strict;

my $file1csv = $ARGV[0];
my $file2csv = $ARGV[1];
my $file3csv = $ARGV[2];

open(ff, "<$file1csv");
my @file1_array = <ff>;
close ff;

open(fg, "<$file2csv");
my @file2_array = <fg>;
close fg;

open(f, "<$file3csv");
my @file3_array = <f>;
close f;

open(g, ">Output.csv");
print g "Name,Color,Food,Point,Task,Stock\n";

foreach my $file1_value (@file1_array)
{
    $file1_value =~s/^\s+|\s+$|\s//igs;
    $file1_value = $file1_value . ",";
    print "Processing\n";

    if($file1_value =~m/^([^\,]*)\,([^\,]*)\,([\w\W]*)\,$/is) 
    {
        my $name = $1; chomp($name);
        my $color = $2; chomp($color);
        my $remaining = $3; chomp($remaining);
        # my $point = $4; chomp($point);
        print "Processing for the name :: $name\n";

        my $task;
        foreach my $file2_value (@file2_array)
        {
            $file2_value =~s/^\s+|\s+$|\s//igs;
            $file2_value = $file2_value.",";

            if($file2_value =~m/$name\,([^\,]*)\,/is)
            {
                $task = $1; chomp($task);
            }
        }

        my $stock;
        foreach my $file3_value (@file3_array)
        {
            $file3_value =~s/^\s+|\s+$|\s//igs;
            $file3_value = $file3_value.",";

            if($file3_value =~m/$color\,([^\,]*)\,/is)
            {
                $stock = $1; chomp($stock);
            }
        }

        open(g, ">>Output.csv");
        print g "$name,$color,$remaining,$task,$stock\n";
    }
}
close g;
print "Completed\n";