Reputation: 527
I am using grep
with -P
(Perl regular expression) to colorize strings:
echo aaa bbb ccc ddd eee | grep --color=always -P "^[^#]*\K(bbb|ccc)|^"
in the above example, I want to colorize the string bbb
and ccc
. However, grep only colorizes the last one (ccc
).
how can I modify my regular expression, so that both strings match and are colorized ?
Upvotes: 2
Views: 577
Reputation: 146
Another alternative is using a perl command to do the match for you.
echo "aaa bbb ccc ddd eee fff" | perl -ne'print if s/(bbb|eee)/\e[1;35m$1\e[0m/g'
Upvotes: 1
Reputation: 18555
Because your regex matches only one alternative: From ^
start until ccc
. But you want multiple matches. This could be achieved by chaining matches to start with use of \G
anchor.
Further it's needed to make the [^#]*
lazy by attaching ?
for not skipping over a match.
echo aaa bbb ccc ddd eee | grep --color=always -P "\G[^#]*?\K(?:bbb|ccc)"
And the regex variant for multiline string.
(?:\G|\n)[^#]*?\K(?:bbb|ccc)
A different approach can be the use of pcre verbs (*SKIP)(*F)
for skipping anything until eol from #
#.*(*SKIP)(*F)|bbb|ccc
Upvotes: 4