Search code examples
windowsperlwhile-loopopendir

add filename column to file perl


My directory

1.csv
2.csv
3.csv

I am trying to capture each file name in a directory and print it to its coresponding file in an additional column along with some additional text and columns.

TEST DATA

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;
}

DESIRED RESULTS

  • 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
    

CURRENT RESULTS

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

I would also like to execute this one script on all files within the dir.


Solution

  • Using perl from command line,

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

    or

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

    or

    local $^I = "~";
    local @ARGV = glob("C:\\directory\\*.csv");
    
    while (<>) { 
      s|^|ID_1234,$ARGV,Copmany,|;
      print;
    }