Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

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?

like image 851
Nate Avatar asked Nov 22 '14 21:11

Nate


People also ask

What does grep return if no match?

Indeed, grep returns 0 if it matches, and non-zero if it does not.

What is grep in shell script?

In Linux and Unix Systems Grep, short for “global regular expression print”, is a command used in searching and matching text files contained in the regular expressions.


1 Answers

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.

like image 131
John1024 Avatar answered Oct 06 '22 12:10

John1024