How to save grep color when stored in a variable or pipe to another command?

I want to use grep in a bash script to find the corresponding lines in the file, highlight the color matches, and then print the results in the table using the column command, Something like this:

 data=`cat file.data | egrep -i --color "$search"` echo $'\n'"col1"$'\t'"col2"$'\t'"col3"$'\t'"col4"$'\n'"$data" | column -t -s$'\t' 

The above code does everything as desired, except that the color is lost.


Here is a simplified example:

enter image description here

As you can see, when I used grep , the results were printed on separate lines and in color, but when I save the results in a variable and then print the variable, the line breaks and the colors disappear.


Is there any way to do what I ask?

+6
source share
1 answer

Use the option --color=always :

 data=$(egrep -i --color=always "$search" file.data) 

By default, grep does not produce color unless the output goes directly to the terminal. This is usually good. The option --color=always overrides this.

If you do not want color, use --color=never .

+5
source

Source: https://habr.com/ru/post/978552/


All Articles