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
4

4 Answers 4

3
grep '^[^#]*print'

Would be print only preceded by non-# characters.

1

Classic solution:

grep -v '^#' <input |grep 'print'
3
  • The issue is that # can be anywhere in the line. I updated my post. Commented Mar 13, 2013 at 15:36
  • The solution greps for any line without the #, then checks for the word 'print'. Commented 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. Commented Mar 13, 2013 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.

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

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

grep -v '#[ ]*print' input_file

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.