Nate
Nate

Reputation: 28374

How to retain grep color when storing in variable or piping to another command?

I'm wanting to use the grep in a bash script to find matching lines in a file, highlight the matches with color, and then print out the results in a 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's a simplified example:

enter image description here

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


Is there any way to do what I'm asking?

Upvotes: 7

Views: 1412

Answers (1)

John1024
John1024

Reputation: 113834

Use the option --color=always:

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

By default, grep does not produce color unless the output is going directly to a terminal. This is normally a good thing. The option --color=always overrides that.

For occasions when you don't want color, use --color=never.

Upvotes: 8

Related Questions