6

I want to search for the occurrence of type . super([A-Za-z]+ , self) in a codebase .

when I am going for $ grep -nr '[s][u][p][e][r][(]' . its showing me all the lines which has super( ,
when I tried to search for the below one with [A-Za-z]+ , I am not getting any result.Can someone please help me to search for all lines in my codebase which has super(*word* , self) in it.

anupam:codebase-2.0$ grep -nr '[s][u][p][e][r][(][A-Za-z]+' .
anupam:codebase-2.0$ 
Adam Katz
  • 3,800
  • 1
  • 24
  • 33
lazarus
  • 185
  • 1
  • 1
  • 10
  • 4
    Why are you using `[s][u][p][e][r][(]` instead of just `super(`? In any case, your regex is likely failing because you are using BRE and not escaping the `+`, i.e. you should use `\+`. – Sparhawk Sep 24 '18 at 10:11
  • thanks a lot @Sparhawk , it worked just fine :) doing $)grep -nr 'super([A-Za-z]\+' – lazarus Sep 24 '18 at 10:15
  • No worries. I've written it out as a more complete answer. – Sparhawk Sep 24 '18 at 11:54
  • assuming you have GNU grep, see https://unix.stackexchange.com/questions/375687/why-doesnt-the-regex-character-produce-a-match-in-sed otherwise see the question marked as duplicate for that question – Sundeep Sep 24 '18 at 13:06

1 Answers1

11

By default, grep uses BRE (basic regular expressions), which means that special characters like + will be interpreted as a literal character. Hence, in GNU grep, it will need to be escaped, i.e. written as \+. (Alternatively, you could use ERE (extended regular expression), with the -E flag; see man grep for more information.) Hence, your command could be written like this:

grep -nr '[s][u][p][e][r][(][A-Za-z]\+'

In addition, the […] surrounding each letter is unnecessary. […] is used to specify a character class, e.g. [ab] could match to either a or b. If there is a single letter in the […], then that is the only match. Hence, your code could be simplified further to

grep -nr 'super([A-Za-z]\+'

N.B. As per Stéphane Chazelas's comment, the \+ construct is a GNU extension. If this doesn't work, you might try \{1,\} instead.

Sparhawk
  • 19,561
  • 18
  • 86
  • 152