2013-07-16 110 views
0

我使用Alan的早期解决方案的下面的解决方案,它将文本文件与管道字符组合起来。谢谢 !Perl:合并多个文本文件和分割文件名

Merge multiple text files and append current file name at the end of each line

#!/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 = <*.txt>) { 
    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 
    } 
} 

如果有人可以帮助加强与以下3所需求的解决方案,将是有益的。

1)在我的文本数据中,某些数据在forllowing格式中的引号内; |"XYZ NR 456"|

上面的解决方案是当我打开最终的combine.csv文件时将这些数据放入不同的列中,是否有办法确保合并时所有数据在管道字符中保持组合。

2)删除一整行,其中它找到字Place_of_Destination

3)当前的解决方案在每一行的末尾添加的文件名。我也想分裂与管道字符的文件名

我的文件名结构是X_INRUS6_08072013.txt,解决方案在每行的末尾添加竖线和文件名X_INRUS6_08072013,我也想要做的就是进一步分裂这个文件名在下面; X | INRUS6 | 08072013

这是可能的,预先感谢所有的帮助。

回答

0

至于你点2,以跳过行,你可以使用一个“未来如果”,用跳绳有关该行的效果:

next if ($line =~ /Place_of_Destination/) 

或“除非”,你的愿望:

unless ($line =~ /Place_of_Destination/) { 
    # do something 
} 

如果我正确理解你正在尝试做什么这个测试是在你的第二个'while'循环中使用。

+0

在打印之前合并文件后,我想要移除包含Place_of_Destination的整行。我不是perl /编码精明的,只是试图用我的需求旧的解决方案。我尝试使用您的输入,但它没有奏效。 – Niriv

相关问题