Question

My bash version:

GNU bash, version 3.2.49(22)-release (i686-pc-cygwin)
Copyright (C) 2007 Free Software Foundation, Inc.

In my .bashrc, I have:

export GREP_OPTIONS='--color=always'

To reproduce the problem, create a file test.txt and write some lines:

test1: apple
test2: orange
test3: cherry

And in bash, do a grep:

grep "test" test.txt > 1

When I check the result, I get something like this:

~ > cat -v 1
^[[01;31m^[[Ktest^[[m^[[K1: apple
^[[01;31m^[[Ktest^[[m^[[K2: orange
^[[01;31m^[[Ktest^[[m^[[K3: cherry

Any idea about this problem? btw, I've setup fileformats=unix.

Était-ce utile?

La solution

The characters you see correspond to codes to change the text color in the terminal. Usually you would want grep to produce color only when its output is going to an interactive terminal. To do that, change

export GREP_OPTIONS='--color=always'

to

export GREP_OPTIONS='--color=auto'

Autres conseils

As pointed by @Joni you need to replace 'always' with 'auto', which will highlight matching strings if (and only if) the output is written directly to the terminal and that terminal is capable of displaying coloured output. Otherwise it will not trash the output with messy characters.

However, a nicer way to make that behaviour default would be to put into your .bash_profile (or .bashrc, or whereever you keep your custom settings):

# grep auto colouring
my_grep_options=(--colour=auto)
alias grep='grep $my_grep_options'

which will always replace your grep call with its preprepared version, so whenever you type:

grep

it will be replaced by:

grep --colour=auto
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top