Is there any way to keep text passed to head, tail, less, etc. to be colored?

27

2

Is there any way to keep colorization of text passed through pipe | to head, tail, less, etc.?

Timofey Gorshkov

Posted 2012-04-27T12:13:47.873

Reputation: 374

Any specific output program? It depends on the program sending the data through the pipe. head, tail, etc aren't the ones removing the colors, it's the program generating the data that usually check if the output is going to the console (colored), a file or pipe (not colored). – KurzedMetal – 2012-04-27T12:56:25.307

Answers

16

I presume you are piping from ls and want to preserve the terminal color codes. You can say ls --color=always (instead of the default of --color=auto), which will preserve the codes, but that won't guarantee that the thing you're piping to knows how to understand them.

If you use glark instead of grep it will try to display with colors.

If you use less with -R it will attempt to display with colors.

phogg

Posted 2012-04-27T12:13:47.873

Reputation: 899

I used this for grep: grep "string" file.txt | head to make sure the result from grep was colored I just changed this to grep "string" file.txt --color=always | head – Emil Stenström – 2017-07-12T13:23:42.683

6I'm piping from git. I'v found that it has similar configuration (eg. git config color.diff always) that keeps colorization. – Timofey Gorshkov – 2012-04-27T13:59:45.123

1@Errandir the problem with that configuration is that it will break any script or command that use git diff output as input because it will always output the ANSI escape codes. – KurzedMetal – 2012-06-14T13:14:10.153

@Errandir, thanks ! I do not have any scripts which rely on a clean output from git diff so this works for me !! Thank you ! – Ashutosh Jindal – 2013-11-06T15:21:36.673

13

It depends on the program that generate the output in the pipe.

head, tail, etc aren't the ones removing the colors, it's the program generating the data that usually check if the output is going to the console (colored), a file or pipe (not colored)

I found another SU Q&A showing how to lie to piping programs to output as if they were sending output to a console (emulating a console with unbuffer)

KurzedMetal

Posted 2012-04-27T12:13:47.873

Reputation: 276

@KurzedMetal How does a program, for example head, tail, etc., detects that it is being piped to another program (so that it can generate data without colors, etc). – Jorge Bucaran – 2016-03-01T05:35:35.587

@JorgeBucaran http://stackoverflow.com/a/7601564/236871

– KurzedMetal – 2016-03-10T13:15:17.830

Is there any way to keep colorization in color=auto mode (to make program think that output goes to console instead of pipe)? – Timofey Gorshkov – 2012-04-27T14:07:15.540