0

I want to use ag to print the classes and their methods in a python file. I thought that this would be easy using:

ag --context=0 --nocolor -os '^\s*(def|class)\s+[_A-Za-z]*' prog.py

but for reasons I don't understand this is also matching blank lines. For example, if you make prog.py the following

class MyFavouriteClass
    def __init__

    def __contains__
        blah    
class MyNextFavouriteClass
    def _repr_

    def __iter__

then it returns the full file, including the blank lines, except for the line containing blah. Of course, I can always pipe the output into something else to remove the blank lines but I'd rather get it right the first time.

I suspect that the problem has nothing to do with the regular expression and, instead, that it's a feature of ag's --context, --after and --before flags but I can't find a combination of these that does what I want.

Any ideas?

  • --context=1 give you one line before and after matches. – cuonglm Aug 10 '16 at 6:50
  • @cuonglm I first tried --context=0 and it still gives me the blank lines. The --context=1 slipped in after a few edits. You're right in that I should have kept --context=0 in the question -- now fixed. Unfortunately, this doesn't solve my problem. – Andrew Aug 10 '16 at 6:51
4

It's not the --context, but the \s* at the start of your regex pattern. It seems ag doesn't search line-by-line like normal grep, but looks at the whole file in one go (or at least several lines at a time). A bit like this Perl one-liner would:

perl -0777 -ne 'print "$&\n" while /^\s*(def|class)\s+[_A-Za-z]*/msg' ../prog.py

So, since \s matches any whitespace, including newlines, it matches the previous empty line, the newline, spaces in front of the next, and then the def keyword. If you add an empty line before the blah line, it's not printed, since blah doesn't fit the pattern.

To get rid the unwanted match, use /^ *... or /^[ \t]*... instead of /^\s*.... (space+asterisk in the first one)

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.