healingtao has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, I have 2 csv files, each with 10 columns,(test1.csv and test2.csv) they both have the same headers and the first 3 columns are the key for each file. What is the quickest way to take column 4,5 and 6 from from test1.csv and replace these columns in test2.csv. It needs to be done by each row because you need to match each row by key because number of rows are different in each file. Thanks

Replies are listed 'Best First'.
Re: replace columns in csv
by Tux (Canon) on Feb 12, 2015 at 08:41 UTC

    Use a CSV parsing module, like Text::CSV_XS and read both files into your perl script. To all the twiddling in your script and write your result back. Likely most of that can be done in about three lines of code using csv (). Show us what you tried so far?


    Enjoy, Have FUN! H.Merijn
Re: replace columns in csv
by i5513 (Pilgrim) on Feb 12, 2015 at 09:55 UTC

    If your csv is simple enough, (your fields doesn't have any "," inside), you can match lines with regex. (The properly way to go is using some csv module from cpan (like Tux told))

    See perlre and search (?<NAME>pattern) to see the use of %+ at the next example:

    #!/usr/bin/perl -w use strict; open my $csv1, "<csv1.csv"; open my $csv2, "<csv2.csv"; open my $csv3, ">csv3.csv"; my %csv1_data; while (<$csv1>) { if (/^(?<first>([^,]*,){3})(?<fields>([^,]*,){3}).*$/) { $csv1_data{$+{first}}=$+{fields}; } } while (<$csv2>) { if (/^(?<first>([^,]*,){3})(?<fields>([^,]*,){3})(?<rest>.*)$/) { if (defined $csv1_data{$+{first}}) { print $csv3 "$+{first}$csv1_data{$+{first}}$+{rest}\n"; } else { print $csv3 $_; } } }