3

I want to grep for the string that contains with dashes like this:

---0 [58ms, 100%, 100%] 

There's at least one dash.

I found this question: How can I grep for a string that begins with a dash/hyphen?

So I want to use:

grep -- -+ test.txt

But I get nothing.

Finally, my colleague tells me that this will work:

grep '\-\+' test.txt

Yes, it works. But neither he nor I don't know why after searched many documents.

This also works:

grep -- -* test.txt
Community
  • 1
  • 1
haithink
  • 70
  • 1
  • 10
  • as far as I know, when you drop quotes, you string `-+` is first interpreted by bash, but with the quotes it passed untouched to the grep command itself, where it is interpreted like a perl regex – d.k Jan 07 '15 at 12:24
  • I know this is not a complete answer, but it is a sort of a pointer to the real cause – d.k Jan 07 '15 at 12:25
  • the `+` sign indicates at least one occurrence of the previous character, also add `^` to indicate beginning of line. http://en.wikipedia.org/wiki/Regular_expression#Syntax – shevski Jan 07 '15 at 12:27
  • 1
    What file does grep list the match in if you run `grep -H -- -* * test.txt`? Does it find it in `test.txt` or some other file? Does `grep -- -\\+ test.txt` work (this is the same as `grep -- '-\+' test.txt`)? – Etan Reisner Jan 07 '15 at 12:30
  • Sorry , redundant star – haithink Jan 07 '15 at 12:31
  • yeah! `grep -- -\\+ test.txt` works! why ? – haithink Jan 07 '15 at 12:32

1 Answers1

4

With -+ you are saying: multiple -. But this is not understood automatically by grep. You need to tell it that + has a special meaning.

You can do it by using an extended regex -E:

grep -E -- "-+" file

or by escaping the +:

grep -- "-\+" file

Test

$ cat a
---0 [58ms, 100%, 100%] 
hell
$ grep -E -- "-+" a
---0 [58ms, 100%, 100%] 
$ grep -- "-\+" a
---0 [58ms, 100%, 100%] 

From man grep:

REGULAR EXPRESSIONS

Basic vs Extended Regular Expressions

In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \).

haithink
  • 70
  • 1
  • 10
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • @haithink `+` is treated differently. It is a meta-character, as described in the man page. See my update. – fedorqui Jan 07 '15 at 12:45
  • 1
    @haithink thanks for the edit! I didn't notice the backslashes weren't showing properly. Also, remember you can always accept an answer when your question is solved. – fedorqui Jan 07 '15 at 12:57