In debugging, I use a lot of 'print' and commenting out it with '#print'. How can I use grep to find the line without '#' before 'print'?

# print <- not detect
#print <- not detect
abc # print <-- not detect
print <- detect

4 Answers 4

grep '^[^#]*print'

Would be print only preceded by non-# characters.


Classic solution:

grep -v '^#' <input |grep 'print'
  • The issue is that # can be anywhere in the line. I updated my post.
    – prosseek
    Mar 13, 2013 at 15:36
  • The solution greps for any line without the #, then checks for the word 'print'.
    – ThaMe90
    Mar 13, 2013 at 15:38
  • 1
    @prosseek Changing the requirements in a question after you receive an answer is not the right way. Better is to ask a new question. Never mind, luckily the solution works also for the changed requirements. But please do not change again the requirements. Ask instead a new question. Mar 13, 2013 at 16:05

The easiest approach is probably going to be to use two greps, piped together.

$ grep 'print' <input | grep -v '#[[:space:]]*print'

With the file input containing your examples, that gives:

print <- detect

That works for all of your examples. Which is probably good enough, but as manatwork and I point out in comments, its going to be very difficult to defeat all the edge cases with grep.

  • For this kind of job, weeding out 80% of the "should not detect" is probably good enough.
    – vonbrand
    Mar 13, 2013 at 16:27

I'm still learning but wouldn't the ff work as well?

grep -v '#[ ]*print' input_file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.