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
prosseek
  • 8,418
  • 16
  • 47
  • 43
  • 4
    See [How to grep on source code without catching comments](http://unix.stackexchange.com/questions/33131/how-to-grep-on-source-code-without-catching-comments) and [How to grep lines which does not begin with “#” or “;”?](http://unix.stackexchange.com/questions/60994/how-to-grep-lines-which-does-not-begin-with-or) first. – manatwork Mar 13 '13 at 15:28
  • 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

4 Answers4

3
grep '^[^#]*print'

Would be print only preceded by non-# characters.

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
1

Classic solution:

grep -v '^#' <input |grep 'print'
H.-Dirk Schmitt
  • 1,999
  • 11
  • 13
  • 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.

derobert
  • 107,579
  • 20
  • 231
  • 279
1

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

grep -v '#[ ]*print' input_file
Michael Mrozek
  • 91,316
  • 38
  • 238
  • 232
morgan_g
  • 61
  • 1
  • 1
  • 4