Linux: preserving color output on match when piping grep to more/less

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, April 02, 2011

Follow me on Twitter as @mattiasgeniar

As a grep user, you’re probably familiar with the following syntax.

# grep 'something' /some/file --color | more

That ‘–color’ parameter highlights the found text so it’s easier to go through a whole bunch of logs. However, that output disappears as soon as you pipe it to more or less to filter the output into pages.

If you change your command, you can prevent that;

# grep 'something' /some/file --color=always | more

If you just use “–color” grep will determine if the output (your terminal, or the input to a second binary (more/less)) can accept these encodings or not. By default, if you pipe it to another tool it would strip all color.

So, just add “–color=always” and you can pass it to a second binary which will preserve color output!



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.