haithink
haithink

Reputation: 70

How can I grep for a string that contains multiple consecutive dashes?

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

Upvotes: 3

Views: 6754

Answers (1)

fedorqui
fedorqui

Reputation: 290315

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 \).

Upvotes: 4

Related Questions