Martin Vegter
Martin Vegter

Reputation: 527

colorize string using grep -P

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

Answers (2)

Boncrete
Boncrete

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

bobble bubble
bobble bubble

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)"

enter image description here

And the regex variant for multiline string.

(?:\G|\n)[^#]*?\K(?:bbb|ccc)

See this demo at regex101


A different approach can be the use of pcre verbs (*SKIP)(*F) for skipping anything until eol from #

#.*(*SKIP)(*F)|bbb|ccc

See another demo at regex101

Upvotes: 4

Related Questions