彩色 grep -- 查看带有突出显示匹配项的整个文件 [英] Colorized grep -- viewing the entire file with highlighted matches

查看:26
本文介绍了彩色 grep -- 查看带有突出显示匹配项的整个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 grep--color=always 标志非常有用.但是,grep 只打印带有匹配项的行(除非您要求提供上下文行).鉴于它打印的每一行都有一个匹配项,突出显示并没有增加尽可能多的功能.

I find grep's --color=always flag to be tremendously useful. However, grep only prints lines with matches (unless you ask for context lines). Given that each line it prints has a match, the highlighting doesn't add as much capability as it could.

我真的很想cat一个文件并查看整个文件,其中突出显示了模式匹配.

I'd really like to cat a file and see the entire file with the pattern matches highlighted.

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

Is there some way I can tell grep to print every line being read regardless of whether there's a match? I know I could write a script to run grep on every line of a file, but I was curious whether this was possible with standard grep.

推荐答案

这里有一些方法:

grep --color 'pattern|$' file
grep --color -E 'pattern|$' file
egrep --color 'pattern|$' file

| 符号是 OR 运算符.要么使用 转义它,要么告诉 grep 搜索文本必须通过添加 -E 或使用 egrep 命令而不是 grep.

The | symbol is the OR operator. Either escape it using or tell grep that the search text has to be interpreted as regular expressions by adding -E or using the egrep command instead of grep.

搜索文本pattern|$"实际上是一个技巧,它将匹配具有 pattern 的行或有结尾的行.因为所有的行都有结尾,所以所有的行都匹配,但行的结尾实际上不是任何字符,所以它不会被着色.

The search text "pattern|$" is actually a trick, it will match lines that have pattern OR lines that have an end. Because all lines have an end, all lines are matched, but the end of a line isn't actually any characters, so it won't be colored.

还可以通过管道传递有色部分,例如对于 less,给 --color 提供 always 参数:

To also pass the colored parts through pipes, e.g. towards less, provide the always parameter to --color:

grep --color=always 'pattern|$' file | less -r
grep --color=always -E 'pattern|$' file | less -r
egrep --color=always 'pattern|$' file | less -r

这篇关于彩色 grep -- 查看带有突出显示匹配项的整个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆