2

I have this regex to remove all print statements from a python codebase:

for f in $(find . -name '*.py') ;
do
egrep -v '^[ \t]print ' $f > $f.new
mv $f.new $f
done

but it doesn't really work..

find . -name '*.py' | xargs egrep '^[ \t]*print'

Still prints out the print statements from my code.. :(

However, I want to modify this to comment out all the lines that have print statements in them(so they arent completely gone from the codebase).

How can I efficiently do this? better still is there an automated way to convert everything to logging framework?

4
  • [ \t] matches exactly one whitespace. You want [ \t]*. Commented Jun 3, 2014 at 7:26
  • Python 2.x or Python 3? Commented Jun 3, 2014 at 7:32
  • 2.x currently. i considered using the 2to3 tool --fix=print but that just converts it into a print fuction and causes a bunch of errors in the codebase also.. Commented Jun 3, 2014 at 7:34
  • [ \t] is the same as \s on most machine Commented Jun 3, 2014 at 15:35

1 Answer 1

5

Sed is the tool for the job.

find . -name '*.py' -exec sed -ri "s/(^\s*)(print.*$)/#\1\2/g" {} \;

For Mac OS X or BSD:

find . -name '*.py' -exec sed -Ei "s/\(^[[:space:]]*\)\(print.*$\)/#\1\2/g" {} \;
Sign up to request clarification or add additional context in comments.

4 Comments

give me an error :: sed: illegal option -- r if i remove -r it give me error : sed: 1: "./scripts/update_hosts.py": invalid command code .
ah, replace the r with E in your case.
if i want to remove print statements instead of comment out?
@NaveenAgarwal find . -name '*.py' -exec sed -ri "s/(^\s*)(print.*$)//g" {} \;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.