39

For example, I have a output:

Hello, this is the output.

(let's say that for example hello is colored red, and the is colored green, and output is colored purple).

Now, let's say that this is the output of a command named x.

If I use this command, the output becomes white:

x | grep hello

I've read that one could use grep --color=always. However, this changes the color to highlight the result I searched for instead of keeping the original line colors.

I want to keep the original line colors. How do I use grep while keeping them?

Z0q
  • 571

2 Answers2

34

You could do this,

 x | grep --color=never hello

To quickly test it, you can do,

ls -l /etc/ --color=always | grep --color=never .
daisy
  • 54,555
  • 9
    The high amount of upvotes suggest this is the answer; but it is a partial answer that doesn't work in general. It works for ls just fine though. – Joshua Apr 15 '16 at 03:06
  • The complete answer is that you probably also need to disable color in the preceding program. See e.g. https://stackoverflow.com/a/63456696/2954547 for how to do this with Git. The answer here shows how to do it with ls. – shadowtalker Jul 14 '21 at 15:50
  • Doesn't work with ls for me. – hepcat72 Aug 19 '22 at 20:50
15

Just a quick hack: when grep is sending output to a pipe, it also commutes to no-changing-color mode

x | grep hello | cat
JJoao
  • 12,170
  • 1
  • 23
  • 45