Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
share|improve this question
4  
    
Should it match (detect) foo # bar print ? –  derobert Mar 13 '13 at 15:37
1  
Should it match print '#';, print ''; # here we print, str='#'; print or str='# print'? There is probably no 100% safe expression without partially rebuilding the language's parser. –  manatwork Mar 13 '13 at 15:38
3  
Try grep '^[^#]*\bprint\b' input. –  manatwork Mar 13 '13 at 15:52
add comment

4 Answers 4

up vote 3 down vote accepted
grep '^[^#]*print'

Would be print only preceded by non-# characters.

share|improve this answer
add comment

Classic solution:

grep -v '^#' <input |grep 'print'
share|improve this answer
    
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
add comment

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.

share|improve this answer
    
For this kind of job, weeding out 80% of the "should not detect" is probably good enough. –  vonbrand Mar 13 '13 at 16:27
add comment

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

grep -v '#[ ]*print' input_file
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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