5

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.

  • what codes are you using to make "yellow"? – thrig Feb 15 '18 at 20:55
8

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.

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.