bash 管道 grep 到 grep 后保留着色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2327191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Preserve colouring after piping grep to grep
提问by Zitrax
There is a simlar question in Preserve ls colouring after grep'ingbut it annoys me that if you pipe colored grep output into another grep that the coloring is not preserved.
在 grep'ing 之后Preserve ls coloring 中有一个类似的问题,但让我烦恼的是,如果您将彩色 grep 输出通过管道传输到另一个 grep 中,则颜色不会被保留。
As an example grep --color WORD * | grep -v AVOID
does not keep the color of the first output. But for me ls | grep FILE
do keep the color, why the difference ?
例如grep --color WORD * | grep -v AVOID
,不保留第一个输出的颜色。但对我来说ls | grep FILE
,保持颜色,为什么不同?
回答by Otto Allmendinger
grep
sometimes disables the color output, for example when writing to a pipe. You can override this behavior with grep --color=always
grep
有时会禁用颜色输出,例如在写入管道时。您可以使用grep --color=always
The correct command line would be
正确的命令行是
grep --color=always WORD * | grep -v AVOID
This is pretty verbose, alternatively you can just add the line
这非常冗长,或者您可以添加该行
alias cgrep="grep --color=always"
to your .bashrc
for example and use cgrep
as the colored grep. When redefining grep
you might run into trouble with scripts which rely on specific output of grep
and don't like ascii escape code.
你.bashrc
比如和使用cgrep
作为彩色的grep。重新定义时,grep
您可能会遇到依赖于特定输出grep
且不喜欢 ascii 转义码的脚本的麻烦。
回答by andersonvom
A word of advice:
一句话忠告:
When using grep --color=always
, the actual strings being passed on to the next pipe will be changed. This can lead to the following situation:
使用时grep --color=always
,传递到下一个管道的实际字符串将被更改。这可能导致以下情况:
$ grep --color=always -e '1' * | grep -ve '12'
11
12
13
Even though the option -ve '12'
should exclude the middle line, it will not because there are color characters between 1
and 2
.
即使该选项-ve '12'
应该排除中间线,它也不会,因为1
和之间有颜色字符2
。
回答by Alex
Simply repeat the same grep command at the end of your pipe.grep WORD * | grep -v AVOID | grep -v AVOID2 | grep WORD
只需在管道末端重复相同的 grep 命令。grep WORD * | grep -v AVOID | grep -v AVOID2 | grep WORD