perl – Search and Replace: Output filename and line numbers

It’s a great idea to change your password often, but what do you do when they are hard coded in hundreds of files?
Yeah, yeah, I know the proper way to fix this is to do some heavy refactoring. Management loves this word, and the typical reaction is the demand for an immediate fix…. like NOW!

Their are a ton of resources for search and replace one liners with perl. However, my environment requires some form of auditing. I could not find any concrete examples that did a search and replace while outputting the file name, line number, and changed line.

perl -pi -e ‘if ($cf ne $ARGV) { $. = 1; $cf = $ARGV; } if (s/cat/dog/g) { print STDERR “$ARGV:$. $_”; }’ t/*

This may not be the cleanest approach, but as well all know with perl, TIMTOWTDI!

Let’s walk through this a bit…

if ($cf ne $ARGV) { $. = 1; $cf = $ARGV; }
This resets $. to 1, when a new file is encountered. If we don’t do this, it will continue with the last line of the last file, thus providing an inaccurate line number for the current file.

$if (s/cat/dog/g) {
If we’ve replaced “cat” with “dog” (found a line where value needs to be changed)

print STDERR “$ARGV:$. $_\n”;
Print output to STDERR:
$ARGV: filename
$. : line number
$_ : changed line

As always, let me know what you think… I’m always open to changes and discussions.

~ by ityndall on May 23, 2013.

Leave a Reply