in reply to Search/Replace within fields of CSV

The safest way to deal with CSV is with a module, and they're easy to use, so there's no reason not to. Let the module cleanly divide up the fields, make the changes you need, and write the results back out to a new file.

#!/usr/bin/env perl use 5.010; use strict; use warnings; use Text::CSV; my $ic = Text::CSV->new({sep_char => ','}) + or die Text::CSV->error_diag(); my $oc = Text::CSV->new({sep_char => ',', eol => $/ }) or die Text::CSV->error_diag(); open my $if, '<', 'infile' or die $!; open my $of, '>', 'outfile' or die $!; my %states = ( '0H' => 'OHIO', '0R' => 'OREGON', ); while( my $r = $ic->getline($if)){ $r->[0] = 'CONDENSED' if $r->[0] eq 'C'; $r->[0] = 'FINAL' if $r->[0] eq 'F'; $r->[4] = $states{$r->[4]} if $states{$r->[4]}; $oc->print($of, $r); } close $if; close $of;

Aaron B.
Available for small or large Perl jobs and *nix system administration; see my home node.

Replies are listed 'Best First'.
Re^2: Search/Replace within fields of CSV
by johnmck (Initiate) on May 08, 2015 at 18:41 UTC
    Thanks very much, Aaron. I was thinking about Text::CSV but I wasn't sure if there was a more practical way to do it. Your code really helps. Thank you.