3

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
3
grep '^[^#]*print'

Would be print only preceded by non-# characters.

1

Classic solution:

grep -v '^#' <input |grep 'print'
  • The issue is that # can be anywhere in the line. I updated my post. – prosseek Mar 13 '13 at 15:36
  • The solution greps for any line without the #, then checks for the word 'print'. – ThaMe90 Mar 13 '13 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. – H.-Dirk Schmitt Mar 13 '13 at 16:05
1

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 '13 at 16:27
1

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.