将文件名列添加到文件perl

时间:2014-10-30 18:31:09

标签: windows perl while-loop opendir

我的目录

1.csv
2.csv
3.csv

我正在尝试捕获目录中的每个文件名,并将其打印到附加列中的相应文件以及一些其他文本和列。

测试数据

hello,josh,12345,2014-10-30

CODE

my $directory = 'C:\directory';

opendir( DIR, $directory );
my @files = readdir(DIR);
closedir(DIR);
foreach (@files) {
    print $_, "\n";
}
while (<>) {
    #Do whatever here
    print;
}

期望的结果

  • 1.csv

    ID_1234,1.csv,Copmany,hello,josh,12345,2014-10-30
    
  • 2.csv

    ID_1234,2.csv,Copmany,hello,josh,12345,2014-10-30
    

当前结果

.
..
1.csv
2.csv
3.csv
hello,josh,12345,2014-10-30

我还想在dir中的所有文件上执行这个脚本。

2 个答案:

答案 0 :(得分:1)

从命令行使用perl,

perl -i~ -F, -lane "BEGIN{$, =','; @ARGV=glob pop} print 'ID_1234',$ARGV,'Copmany',@F" *.csv

perl -i~ -pe "BEGIN{ @ARGV=glob pop} s|^|ID_1234,$ARGV,Copmany,|" *.csv

local $^I = "~";
local @ARGV = glob("C:\\directory\\*.csv");

while (<>) { 
  s|^|ID_1234,$ARGV,Copmany,|;
  print;
}

答案 1 :(得分:0)

怎么样:

my $directory = 'C:\directory';

opendir( DIR, $directory );
my @files = readdir(DIR);
closedir(DIR);
foreach (@files) {
   print qq(ID_1234,$_,Copmany,hello,josh,12345,2014-10-30\n);
}