11

Say I have output from a command that is colorized for the terminal. I want to match any line that contains the color yellow. How can I do this in grep, eg: mycommand -itSomtimesPrintsLinesWithYellowColorCodes | grep -e "?????"

Note: This is NOT about colorizing the output of grep, or adding any colors. It's only about how to filter/match colored of input coming into grep.

2

1 Answer 1

10

Let's use tput to generate the color code for your terminal for yellow and black:

$ yel=$(tput setaf 3)
$ blk=$(tput setaf 0)

Let's examine what the yellow code actually includes:

$ echo -n "$yel" | hexdump -C
00000000  1b 5b 33 33 6d                                    |.[33m|
00000005

Now, we can use grep to search for the yellow color code and print the string that matches from the beginning of the yellow code to the next code, whatever that code is:

$ echo "abc ${yel}Yellow${blk} def" | grep -Eo $'\x1b\[33m.[^\x1b]*\x1b\[....'
Yellow 

Note that the color code for yellow includes [ which grep considers to be a regex active character. Thus, to match a literal [, we need to escape it for grep. To do this, we use bash's $'...' to define the color code with [` escaped.

We used two options to grep: -E tells grep to use (modern) extended regular expressions. The option -o tells grep to print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

It is likely that there is more than one code to produce yellow on your terminal. You will want to examine the output of whatever command you are using to determine what codes are being used and include them in your grep command.

2
  • 1
    "-E, --extended-regexp: PATTERNS are extended regular expressions", "-o, --only-matching: show only nonempty parts of lines that match"
    – jave.web
    Aug 2 at 6:25
  • @jave.web Good suggestion. I added that info to the answer.
    – John1024
    Aug 6 at 22:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .