1

I am trying to formulate a regex expression for use with grep such that I find a static word present at the beginning of each line, followed by only one word from a list of options.

That is, I matches I want are of the form: StaticWord-opt1, StaticWord-opt2, etc.

This almost works:

grep -E "^StaticWord-[(opt1)?(opt2)?(opt3)?]+" fileToCheck

But I get matches like: StaticWord-opt1(, StaticWord-p, and StaticWord-1

Since a valid match is only if we have a single instance of op1, opt2, or opt3, I changed the expression to:

grep -E "^StaticWord-[(opt1)?(opt2)?(opt3)?]{1}" fileToCheck

At which point I get only matches like the latter two of the list outlined above.

My logic for the expression is "StaticWord- is anchored at the beginning ^ followed by any of the following [ ] groups ( ), each of which may or may not be present ?. Lastly, we must have only one from the list {1}.

  • 3
    ^StaticWord-(opt1|opt2|opt3) – jordanm Nov 17 '15 at 18:23
  • @don_crissti, Sorry. opt1, opt2, and opt3. – sherrellbc Nov 17 '15 at 18:23
  • Should "StaticWord-opt1morestuff" match or not match? (Should the line end with opt1, opt2, or opt3?) – Jeff Schaller Nov 17 '15 at 18:36
  • You're getting bad results because you're using brackets which do something different. Just do (opt1|opt2|opt3) without the brackets like @jordanm suggested. – cprn Nov 17 '15 at 18:38
  • @JeffSchaller, My requirements are only that StaticWord-opt1 be present. Using what was suggested in the comments above I was able to achieve that. What must be changed in order to prevent further matches? – sherrellbc Nov 17 '15 at 18:38
2

In case jordanm doesn't convert their comment to an answer, I'll expand on it:

You want to use the | character to say "opt1 or opt2 or opt3". Additionally, if you only want one of those to appear, you do not want to use +, which means "one or more". This gets you closer:

grep -E "^StaticWord-(opt1|opt2|opt3)" fileToCheck

... but then you have the question about the remainder of the line. If you want nothing else on the line, use:

grep -E "^StaticWord-(opt1|opt2|opt3)\$" fileToCheck

(where I escaped the dollar sign from the shell so that grep sees it as the end-of-line marker).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.