The command you're looking for is grep
, and the regular expression you want is b[[:alnum:]]*[ig][[:alnum:]]*o
.
[[:alnum:]]
will match a single alphanumeric character.
*
will match any number (including zero) of the previous expression.
[ig]
will match a single i
or g
.
- All other characters (
b
and o
) in this particular regular expression matches themselves.
The use of [[:alnum::]]*
rather than .*
avoids matching words that contain spaces.
grep
is used like
grep OPTIONS 'EXPRESSION' INPUT-FILES
and will output the lines matching EXPRESSION
to its standard output (the terminal, in this case).
In this case, you would want to use the -w
and -o
options, which forces the expression to match words (strings of characters surrounded by non-word characters) and to only return the matched data (not the whole line).
$ grep -w -o 'b[[:alnum:]]*[ig][[:alnum:]]*o' words
bio
bgo
You mentioned that you wanted to highlight the matched words. This is something that GNU grep
can do. I'm dropping the -o
option here to get the whole line of each match, otherwise you'll just get the same result as previously, but highlighted, which would be boring.
$ grep --color -w 'b[[:alnum:]]*[ig][[:alnum:]]*o' words
bio jdjjf
dgdhd bgo
As you can see, this only shows the matches on lines that contain matches. To see the full input (even lines with no match), with the matches highlighted, we have to drop the -w
option and do
$ grep --color -E '\bb[[:alnum:]]*[ig][[:alnum:]]*o\b|$' words
boo djhg
bio jdjjf
dgdhd bgo
ghhh
We had to add the -E
option since |
is an extended regular expression. The \b
will match at any word boundary.
boo
does not fulfil the criteria, surely?