How to use grep regex to include optional character

I need to have a match for the optional character , (comma punctuation marks) in grep regex. I want to match the following in input:

-a,
-b,
-c
-d
--foo
-e,
--bar

So I write

grep -w -E -- '-[abcd],' input.txt

But, I only get:

-a,
-b,

But, I want output as:

-a,
-b,
-c
-d

So how do you use grep regex to include optional character , (comma punctuation marks)?

1 Like

Try grep regex as follows

grep -w -E -- '-[abcd],?' input.txt

Outputs:

-a,
-b,
-c
-d

Understanding grep regular expression (regex) operators

Here are three main operators to match character

  1. ? : 0 or 1 preceding character match (The preceding item is optional and will be matched, at most, once) This is what you need.
  2. * : 0 or many character match (The preceding item will be matched zero or more times)
  3. + : 1 or many character match (The preceding item will be matched one or more times)

Please note that , (comma punctuation marks) preceding at once should be as follows:

grep -w -E -- '-[abcd],?' input.txt

And NOT as follow:

grep -w -E -- '-[abcd]?,' input.txt

Do read grep manual page and my tutorial page:
https://www.cyberciti.biz/faq/grep-regular-expressions/
And
https://www.cyberciti.biz/faq/howto-use-grep-command-in-linux-unix/

1 Like