我发现grep的——color=always标志非常有用。但是,grep只打印匹配的行(除非您要求上下文行)。假设它打印的每一行都有一个匹配项,那么高亮显示并不能增加尽可能多的功能。

我真的想猫一个文件,并看到整个文件与模式匹配突出显示。

是否有某种方法可以告诉grep打印正在读取的每一行,而不管是否有匹配?我知道我可以编写一个脚本来在文件的每一行上运行grep,但我很好奇标准grep是否可以做到这一点。


当前回答

使用ripgrep,即rg: https://github.com/BurntSushi/ripgrep

rg - passthru……

颜色是默认的:

  rg -t tf -e  'key.*tfstate' -e dynamodb_table
       --passthru
       Print both matching and non-matching lines.

       Another way to achieve a similar effect is by modifying your pattern to
       match the empty string. 
       For example, if you are searching using rg foo then using 
       rg "^|foo" instead will emit every line in every file searched, but only
       occurrences of foo will be highlighted. 
       This flag enables the same behavior without needing to modify the pattern.

亵渎神明,没错,但格雷普已经沾沾自喜了。

安装ripgrep

你再也回不去了。

其他回答

这是一种方法,

wc -l filename

会给你行数,比如NN,你能做什么

grep -C NN --color=always filename

grep的-z选项也非常灵活!

cat file1 | grep -z "pattern"

你可以从https://github.com/kepkin/dev-shell-essentials上使用我的高亮脚本

它比grep更好,因为您可以用自己的颜色突出显示每个匹配。

$ command_here | highlight green "input" | highlight red "output"

我使用以下命令来达到类似的目的:

grep -C 100 searchtext文件

这将说grep打印100 * 2行上下文,在高亮显示的搜索文本之前和之后。

另一个回答提到了grep的-Cn开关,其中包含n行Context。当egrep模式看起来太复杂,或者当我在一台没有安装rcg和/或ccze的机器上时,我有时会用n=99作为一种快速而肮脏的方式来获得[至少]满屏的上下文。

我最近发现ccze是一个更强大的着色剂。我唯一的抱怨是它是面向屏幕的(就像less一样,我从不使用这个原因),除非你为“原始ANSI”输出指定-A开关。

上面提到的RCG +1。它仍然是我的最爱,因为它是如此简单,自定义在一个别名。类似这样的东西通常在我的~/.bashrc中:

alias tailc='tail -f /my/app/log/file | rcg send "BOLD GREEN" receive "CYAN" error "RED"'