
我有以下foo.txt
文件:
This is the first line.
This is the middle line.
This is the last line.
我試圖僅透過單字來 grep 中線middle
並返回周圍環境(例如),這樣我就可以突出顯示整個句子(這在與上下文選項一起使用時特別有用)。
它做沒有顏色的工作:
$ grep -o --color=none '.\+ middle .\+' foo.txt
This is the middle line.
但同樣的命令不使用顏色:
$ grep -o --color=auto '.\+ middle .\+' foo.txt
(empty line)
注意:沒有-o
它沒有任何區別。
儘管它在僅過濾行的前半部分時有效:
$ grep -o --color=auto '.\+ middle' foo.txt
This is the middle
但下半場則不然 ( 'middle .\+'
)。
為什麼這不能按預期工作以及如何修復它?這是一個錯誤還是由於某種原因我無法同時使用兩個正規表示式?
在 OS X 上測試:
$ grep --version
grep (BSD grep) 2.5.1-FreeBSD
雖然它似乎可以在Linux上運行,所以我很困惑。
答案1
當您使用帶有顏色選項的 grep 時,它會產生額外的轉義字元序列,告訴終端開啟或關閉顏色,這些序列會帶來無法正確解釋並導致意外結果的風險。
您可以透過捕捉 grep 的輸出來查看這些內容
沒有顏色
將 grep 輸出傳送到output.txt
% grep -o --color=none '.\+ middle .\+' foo.txt > output.txt
% cat -etv output.txt
This is the middle line.$
有顏色
使用選項強制顏色--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$
這些轉義序列可能導致了問題。