合并csv文件并在Perl中重新编号

时间:2014-02-20 09:37:15

标签: perl merge

我正在导出大量的csv文件(> 2000),我想将它们合并到一个大文件中,但我还需要重新编号节点。这是一个让它易于理解的例子

Export01.csv

Node Number, X [ m ], Y [ m ], Z [ m ], massflow [ kg/s ]

0, 9.65997651e-02, 2.19999515e-02, -9.62853723e-04

1, 9.65997726e-02, 2.20612120e-02, -9.62852850e-04

2, 9.65411291e-02, 2.20607035e-02, -9.81093850e-04

3, 9.65427309e-02, 2.19999403e-02, -9.80595709e-04

4, 9.65997800e-02, 2.21210755e-02, -9.62849939e-04

5, 9.65387151e-02, 2.21203361e-02, -9.81845544e-04

[Faces]

0, 1, 2, 3

1, 4, 5, 2

Export02.csv

Node Number, X [ m ], Y [ m ], Z [ m ], massflow [ kg/s ]

0, 1.01048574e-01, 1.68000087e-02, 5.73535908e-05

1, 1.01048581e-01, 1.68612748e-02, 5.73558682e-05

2, 1.00987844e-01, 1.68607645e-02, 4.80981507e-05

3, 1.00989506e-01, 1.67999957e-02, 4.83512231e-05

4, 1.01048574e-01, 1.69211421e-02, 5.73557772e-05

5, 1.00985348e-01, 1.69204008e-02, 4.77131580e-05

6, 1.01048581e-01, 1.69791635e-02, 5.73566977e-05

7, 1.00984685e-01, 1.69786215e-02, 4.76094247e-05

[Faces]

0, 1, 2, 3

1, 4, 5, 2

4, 6, 7, 5

Export02.csv 的节点号必须从最后一个节点在Export01.csv结束的位置开始。因此 Export02.csv 中的节点0 变为节点6 。这也是为了面子。此外, Export02.csv 0,1,2,3 中的第一个面将变为6, 7, 8, 9。所以新文件将是:

Node Number, X [ m ], Y [ m ], Z [ m ], massflow [ kg/s ]

0, 9.65997651e-02, 2.19999515e-02, -9.62853723e-04

1, 9.65997726e-02, 2.20612120e-02, -9.62852850e-04

2, 9.65411291e-02, 2.20607035e-02, -9.81093850e-04

3, 9.65427309e-02, 2.19999403e-02, -9.80595709e-04

4, 9.65997800e-02, 2.21210755e-02, -9.62849939e-04

5, 9.65387151e-02, 2.21203361e-02, -9.81845544e-04

6, 1.01048574e-01, 1.68000087e-02, 5.73535908e-05

7, 1.01048581e-01, 1.68612748e-02, 5.73558682e-05

8, 1.00987844e-01, 1.68607645e-02, 4.80981507e-05

9, 1.00989506e-01, 1.67999957e-02, 4.83512231e-05

10, 1.01048574e-01, 1.69211421e-02, 5.73557772e-05

11, 1.00985348e-01, 1.69204008e-02, 4.77131580e-05

12, 1.01048581e-01, 1.69791635e-02, 5.73566977e-05

13, 1.00984685e-01, 1.69786215e-02, 4.76094247e-05

[Faces]

0, 1, 2, 3

1, 4, 5, 2

6, 7, 8, 9

7, 10, 11, 8

10, 12, 13, 11

对这样的程序进行编程的最有效方法是什么?

1 个答案:

答案 0 :(得分:0)

试试这个。

#/usr/bin/perl -w

use strict;
use warnings;

my $i = 0;
my $filename = "final.csv"; # created file name

open my $final_fh, ">>", $filename;

while (defined(my $file = glob '*.csv')) { # csv files in the same dir of the script
  open my $fh, "<", $file;  # lexical file handles, automatic error handling

  while (defined( my $line = <$fh> )) {
    my @parts = split(/,\s*/, $line);
    shift @parts; #remove index

    print $final_fh "$i, " . join(", ", @parts) . "\n";
    $i++;
  }
  close $fh;
}
close $final_fh;