First: use a module to work with csv files, and a good one is Text::CSV
Now, for a job like this, this one time, a simple filter is OK:
my $line = q(first,last John,Smith Francis,);
$line =~ s/.*,\K$/filled_last_field/;
The greedy .*
matches up to the last instance of the following pattern (comma here) on the line.
The \K
form of the positive lookbehind
drops all previous matches so they are not consumed; so it only replaces the pattern after it (adds the phrase in this case, as needed).
If you'd like to first replace the file then you read it line by line and write the changed lines to a new file, which then gets moved over the old one.
open my $fh, '<', $file or die "Can't open $file: $!";
open my $fh_out, '>', $new_file or die "Can't open $new_file: $!";
while (<$fh>) {
print $fh_out s/.*,\K$/filled_last_field/r;
}
# Move $new_file to $file
where I've used the /r
modifier, which returns the modified string, just right for the print
here. See this post and this post (for example) for full programs of this kind with relevant details.
Or, with Path::Tiny
path($file)->edit_lines( sub { s/.*,\K$/ADDED/ } )
Methods to edit a file directly were added in the version 0.077. Many of the module's methods have their _utf8
counterparts, and there is edit_lines_utf8 as well.
In a one-liner
perl -wpe's/.*,\K$/ADDED/' file.csv > new_file.csv
or, to change the input file in-place
perl -i -wpe's/.*,\K$/ADDED/' file.csv
or, to change it and also keep a backup
perl -i.bak -wpe's/.*,\K$/ADDED/' file.csv