Linux – How to grep two things where one has option -w

greplinuxregular expression

I have a json file from where I want to get the value of two items which are in an array using grep. Let's say I'm trying to get data from values foo and bar, the problem is that baralso matches megabarso I have to grep it with option -w.
The problem comes when trying to find them at the same time, as I have to grep for one value OR the other.
From this question, I managed to get a bit closer to what I'm looking for but my result was something like:

grep -E '(foo|-w bar)' file
 "foo": "59766",
 "foo": "59770",
 "foo": "59774",
 "foo": "59778",
 "foo": "59782",
 "foo": "59786",

Any idea on how to do it?

Best Answer

The word boundary has a similar effect to -w, but can be used as part of the expression.

‘\b’
Match the empty string at the edge of a word.
[...]
‘\<’
Match the empty string at the beginning of word.
‘\>’
Match the empty string at the end of word.

To match bar only when it's the whole word, but foo anywhere (including inside longer words):

grep -E 'foo|\<bar\>'