-2

File1.csv、File2.csv、...、File1000.csv という名前の 1000 個のファイルを含むフォルダーがあり、それぞれにセミコロン (;) で区切られたデータ値の行が含まれているとします。

そのフォルダー内のすべてのcsvファイルを1つに「マージ」するには、Perlスクリプトが必要です。各ファイルを次々に追加し、各行の最後に現在処理中のファイルの名前を含む別のデータ列を追加します例: ";File2")。

スティーブ

4

1 に答える 1

1

Text::CSVCSVの解析に使用できます。次のスクリプトは、CSVファイルを含むディレクトリ内から実行されます。再帰的ではありません(aglobが使用されています)。ファイルを再帰的に検索する必要がある場合は、File::FindPerlモジュールを使用できます。

#!/usr/bin/env perl

use strict;
use warnings;

use Text::CSV;

my $csv = Text::CSV->new( { 'sep_char' => ';' } );

open my $fho, '>', 'combined.csv' or die "Error opening file: $!";

while ( my $file = <*.csv> ) {
    open my $fhi, '<', $file or die "Error opening file: $!";
    ( my $last_field = $file ) =~ s/\.[^\.]+$//;  # Strip the file extension off

    while ( my $row = $csv->getline($fhi) ) {
        $csv->combine( @$row, $last_field );  # Construct new row by appending the file name without the extension
        print $fho $csv->string, "\n";        # Write the combined string to combined.csv
    }
}
于 2012-05-28T11:22:02.650 に答える