I came here across the command grep -E '(^| )ABC( |$)' file1 I am confused how to interpret the regular expression therein, because I know the ^ and $ character as beginning and end signifier, but in here they are not at the very beginning or end because of the bracket, ^ is sometimes used to negate a set of character, but I have seen this usage only in [^....] like expression.

Could someone explain step by step the meaning of this regex ?


It means that grep should search for ABC string only at the beginning of the line OR after space, moreover this string has to end with another space OR the end of the line.

In other words someone wanted to search for a strings which form whole words. However this regexp has many issues, namely there could be many other characters before and after word (at least in natural language), i.e. (,),.,;,:,,,..., etc.

Thus, it is better to use -w option of grep, alternatively play with boundaries: \b or \</\>.

  • Not all implementations of grep have -w, \b or \<, none of which are standard. The GNU one doesn't work with multibyte locales (echo épris | grep -w pris matches). – Stéphane Chazelas Feb 24 '15 at 22:30

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.