合并多个文本文件,并在每行的末尾附加当前文件名 [英] Merge multiple text files and append current file name at the end of each line

查看:174
本文介绍了合并多个文本文件,并在每行的末尾附加当前文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为File1.csv,File2.csv,...,File1000.csv的文件夹,并且每个文件都包含一些以分号分隔的(;)数据值的行

b
$ b

我需要一个Perl脚本来将所有文件夹中的所有csv文件合并为一个,每个文件一个接一个地追加,另外在每行的末尾添加另一个数据列,正在处理的文件(没有结尾,例如; File2)。

Steve

解决方案

Text :: CSV 可以用来解析CSV。以下脚本将在包含CSV文件的目录中运行。它不是递归的( glob 已被使用)。如果您需要递归查找文件,则可以使用 File :: Find Perl模块。

 #!/ usr / bin / env perl 

使用strict;
使用警告;

使用Text :: CSV;

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

打开我的$ fho,'>','combined.csv'或死掉Error opening file:$!;

while(my $ file =< *。csv>){
打开我的$ fhi,'<',$ file或者dieError opening file:$!
(my $ last_field = $ file)=〜s / \。[^ \。] + $ //; #($行= $ csv-> getline($ fhi)){
$ csv-> combine(@ $ row,$ last_field)将文件扩展名关闭

; #通过附加文件名构建新行,不带扩展名
print $ fho $ csv-> string,\\\
; #将合并的字符串写入combined.csv
}
}


let's say I have a folder with a thousand files named File1.csv, File2.csv, ..., File1000.csv and every one contains some lines of semicolon-separated (;) data values.

I need a Perl script to "merge" all the csv files in that folder into one by appending each file one after another and also adding another data column at the end of each line with name of the file being currently processed (without the ending, e.g. ";File2").

Steve

解决方案

Text::CSV can be used to parse CSV. The following script is to be run from within the directory containing the CSV files. It is not recursive (a glob has been used). If you require it to recursively find files, you can use the File::Find Perl module.

#!/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
    }
}

这篇关于合并多个文本文件,并在每行的末尾附加当前文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆