Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to preserve colouring after piping grep to grep in Linux?
In order to preserve colouring after using pipes between grep commands, we must first understand what the grep command is and how it handles output coloring in Linux.
The grep command in Linux is used to filter searches in files for a particular pattern of characters. It is one of the most used Linux utility commands to display lines that contain the pattern we are searching for. The pattern we search for is typically called a regular expression.
By default, grep displays colored output when writing directly to a terminal, but this coloring is lost when output is piped to another command because grep detects it's not writing to a terminal.
Basic Grep Syntax
grep [options] pattern [files]
Common grep options include:
-c : Lists only a count of the lines that match a pattern -h : Displays the matched lines only -i : Ignores case for matching -l : Prints filenames only -n : Display the matched lines and their line numbers -v : Prints out all lines that do not match the pattern -r : Recursively search subdirectories --color=always : Forces colored output even when piping
The Color Problem with Pipes
Consider a simple file with three numbers:
$ cat bar 11 12 13
When we use grep normally, the output may have colors in the terminal:
grep -e '1' *
bar:11 bar:12 bar:13
However, when piping grep output to another grep command, the coloring is lost:
grep -e '1' * | grep -ve '12'
bar:11 bar:13
Solution − Using --color=always
To preserve coloring when piping, use the --color=always option with the first grep command:
grep --color=always -e '1' * | grep -ve '12'
For multiple pipes, you can apply --color=always to each grep command where you want colored output:
grep --color=always -e '1' * | grep -ve '12' | grep --color=always -e '1'
Alternative Methods
You can also set the GREP_OPTIONS environment variable to always use colors:
export GREP_OPTIONS='--color=always'
Or create an alias in your shell configuration file:
alias grep='grep --color=always'
Key Points
Grep automatically disables colors when output is piped to maintain compatibility
Use
--color=alwaysto force colored output in pipesThe
--color=autooption enables colors only for terminal output (default behavior)Setting
--color=nevercompletely disables colored output
Conclusion
To preserve grep coloring when using pipes, add the --color=always option to your grep commands. This forces grep to maintain colored output even when piping to other commands, making it easier to visually identify matched patterns in complex command chains.
