13

Hi im new to ack (actually started half an hour ago). Im impressed by the quality of the search results.

But in my source files there are a lot of comments and if i search for a class/function-name i get about 20 results with commented lines and 2 with the actual code.

Is there a way to exclude text after // and # or between /* */?

2

2 Answers 2

4

You could skip single line comments with something like this;

# ignore matches after //
ack '^[^//]*word'
# ignore matches after #
ack '^[^#]*word'

If you are using ag instead, remember that it does multi-line matches:

# ignore matches after //
ag '^[^\n\r//]*word'
# ignore matches after #
ag '^[^\n\r#]*word'
3
  • Why is the [^\r\n] necessary? Doesn't ack only do single-line matches?
    – Lucretiel
    Commented May 6, 2016 at 19:09
  • Thanks. I think you are right, edited. Ack returns single-line matches, but ag returns multi-line matches.
    – sina
    Commented May 7, 2016 at 9:38
  • Also, [^//] won't do what you expect it too. You'd need a more complex matcher.
    – Lucretiel
    Commented May 9, 2016 at 19:10
0

You don't. Instead, you tag your source.

Skipping comments would mean parsing the input on the fly, which is generally speaking slow. Moreover, each programming language has a different syntax for comments, which makes implementing this non-trivial. While you could roll your own regex -- e.g. for C use something like this: \/\*(\*(?!\/)|[^*])*\*\/ -- these patterns are complex and more trouble than their worth for the quick searching that ack, ag, and grep are designed for. What you're really looking is a way to navigate your code via functions and classes; this is what tagging one's code is for: check out universal-ctags, http://docs.ctags.io/en/latest/.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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