为什么用颜色 grepping 不返回任何东西?

ken*_*orb 7 command-line osx grep bsd

我有以下foo.txt文件:

This is the first line.
This is the middle line.
This is the last line.
Run Code Online (Sandbox Code Playgroud)

而且我正在尝试仅通过单词 grep 中间行middle并返回周围环境(例如),因此我可以突出显示整个句子(这在与上下文选项一起使用时特别有用)。

确实可以在没有颜色的情况下工作:

$ grep -o --color=none '.\+ middle .\+' foo.txt
This is the middle line.
Run Code Online (Sandbox Code Playgroud)

但相同的命令不适用于颜色:

$ grep -o --color=auto '.\+ middle .\+' foo.txt
(empty line)
Run Code Online (Sandbox Code Playgroud)

注意:没有-o它没有任何区别。

虽然它仅在过滤行的前半部分时有效:

$ grep -o --color=auto '.\+ middle' foo.txt
This is the middle
Run Code Online (Sandbox Code Playgroud)

但不是下半场 ( 'middle .\+')。

为什么这不能按预期工作,我该如何解决?这是一个错误还是由于某种原因我不能同时使用两个正则表达式?


在 OS X 上测试:

$ grep --version
grep (BSD grep) 2.5.1-FreeBSD
Run Code Online (Sandbox Code Playgroud)

虽然它似乎适用于 Linux,但我很困惑。

the*_*fog 4

当您将 grep 与颜色选项一起使用时,它会产生额外的转义字符序列,告诉终端打开或关闭颜色,这些序列会带来无法正确解释并导致意外结果的风险。
您可以通过捕获 grep 的输出来查看这些内容

没有颜色

将 grep 输出发送到output.txt

% grep -o --color=none '.\+ middle .\+' foo.txt > output.txt
% cat -etv output.txt 
This is the middle line.$
Run Code Online (Sandbox Code Playgroud)

有颜色

使用选项强制颜色--color=always。如果您重定向 grep 输出,它会 - 如果可能 - 出于您突出显示的确切原因关闭颜色,转义字符可能会产生副作用。

% grep -o --color=always '.\+ middle .\+' foo.txt > output.txt
% cat -etv output.txt                                             
^[[01;31m^[[KThis is the middle line.^[[m^[[K$
Run Code Online (Sandbox Code Playgroud)

这些转义序列可能导致了问题。