Sridhar-Sarnobat Sridhar-Sarnobat - 1 month ago 4x
Perl Question

Comment out multiline log statements using perl one liner regex substitution

I have a perl one-liner that works when log statements are on a single line:

find -type f -iname "*java" | xargs -d'\n' -n 1 perl -i -pe 's{(log.*((info)|(debug)).*)}{//$1}gi'

But trying to modify this to work on multiple lines is tricky. I know that the
modifier will match newlines, but how do I get it to comment out subsequent lines (i.e. up to
assuming the log string doesn't have it)?

I'm fine with a solution that makes multi-line log statements into single-line log statements too. I'll also accept C-style comments (though it would be nice to find a solution for C++ style comments).

(Don't tell me to turn off logging. Anyone who's actually tried that will realize how brutally complicated that is in non-trivial applications.)


Just a general idea (please adapt to your case...)

...perl -i -p0e 's{(log.*?((info)|(debug)).*?;)}{ $1 =~ s!^|\n!\n//!gr }gsei'


  • .*? instead of .* to behave non-greddy
  • -p0e to process the full text as a single record
  • $1 =~ s!^|\n!\n//!gr to make extra processing of internal newlines

Please test it before application...