Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep command that matches lines with EXACTLY 2 '*'

Tags:

regex

grep

I need help figuring out a command that will search a file and display lines that include exactly 2 *.

  • Valid matches examples: **, *red*, manche*ste*r
  • Invalid matches examples: *, ***, mache*s*te*r

What I have so far is:

grep ‘\*.*\*’ filename.txt

But this displays lines that have at least two * but not exactly two. And I can't see to find a way to do that.

like image 728
omonoia Avatar asked Dec 20 '25 18:12

omonoia


1 Answers

You may use

grep '^[^*]*\*[^*]*\*[^*]*$' filename.txt

The regex matches a string that contains exactly two asterisks with any other chars before, after and in-between them.

Pattern details

  • ^ - start of string
  • [^*]* - 0+ chars other than *
  • \* - a *
  • [^*]*\*[^*]* - 0+ chars other than *, a * and again 0+ chars other than *
  • $ - end of string.
like image 86
Wiktor Stribiżew Avatar answered Dec 23 '25 09:12

Wiktor Stribiżew