AvdnhracNTAd9ex
AvdnhracNTAd9ex

Reputation: 57

Make grep colour only capture groups

How do I only colour text in grep that has been matched by a group?

Example:

printf "Jon Skeet" | grep -P "Sk(.)(?:\1t)"

Prints out "Jon Skeet" (with "Skeet" coloured).

I want it to colour only the first 'e' (ie. "Jon Skeet").


EDIT:

printf "zazbzcz" | grep -P "(.)((?<=.)\1){3}"

prints out nothing, but how can I have it print out

zazbzcz

EDIT 2:

Perhaps I wasn't clear.

This will be run in a script where I want it to highlight as follows (therefore I will not know where and which letter or number it will be):

sdsfsisj

asdlwlxaleldoxwy

pqk5z5x5c5w5qas

Note: it will always be exactly one character that needs to be highlighted
(in an ambiguous case, any of them may be highlighted)

Upvotes: 2

Views: 1646

Answers (2)

sjgallen
sjgallen

Reputation: 239

For the second part:

printf "zazbzcz" | grep --color=always "z"

prints out the results you want. It did for me, at least.

I have not figured out the right regex to only color the first instance of a character which is what you want for the first part. I do know that

printf "Jon Skeet" | grep --color=always "e" 

prints out both e being colored.

Edit: To allow for variables using Bash.

string_name=zazbzcz variable_name=z printf $string_name | grep --color=always $variable_name

I hope this helps you.

Edit 2

The following is a bash script that takes 2 arguments.

The first argument takes string or text. The second argument takes a character to colorize.

#!/bin/bash text=${1} char_colorized=${!#} printf $text | grep --color=always $char_colorized

So if you call your file colorize.sh and you have already made it executable. (chmod)

All you should need to do is the following:

./colorize.sh zazbzcz z

This is the best I can do to answer the question as I understand it.

Again, I hope it helps.

Upvotes: 0

Benjamin W.
Benjamin W.

Reputation: 52451

Grep colours everything that matched, you can't make it colour just capture groups. If you want to highlight just that single letter, but use the same regular expression, you can use a positive look-ahead so it doesn't become part of the match:

grep -P '(?<=Sk)(.)(?=\1t)'

Upvotes: 2

Related Questions