我发现grep的——color=always标志非常有用。但是,grep只打印匹配的行(除非您要求上下文行)。假设它打印的每一行都有一个匹配项,那么高亮显示并不能增加尽可能多的功能。
我真的想猫一个文件,并看到整个文件与模式匹配突出显示。
是否有某种方法可以告诉grep打印正在读取的每一行,而不管是否有匹配?我知道我可以编写一个脚本来在文件的每一行上运行grep,但我很好奇标准grep是否可以做到这一点。
我发现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
你再也回不去了。
其他回答
另一种肮脏的方式:
grep -A80 -B80 --color FIND_THIS IN_FILE
我做了一个
alias grepa='grep -A80 -B80 --color'
把bashrc打印出来。
这是一种方法,
wc -l filename
会给你行数,比如NN,你能做什么
grep -C NN --color=always filename
这里有一些方法:
grep --color 'pattern\|$' file
grep --color -E 'pattern|$' file
egrep --color 'pattern|$' file
|符号是OR运算符。要么使用\转义它,要么通过添加-E或使用egrep命令而不是grep告诉grep搜索文本必须解释为正则表达式。
搜索文本“pattern|$”实际上是一个技巧,它将匹配具有模式的行或具有结束的行。因为所有的行都有一个结尾,所有的行都被匹配,但是一行的结尾实际上不是任何字符,所以它不会被着色。
要通过管道传递有颜色的部分,例如向less传递,请向——color提供always参数:
grep --color=always 'pattern\|$' file | less -r
grep --color=always -E 'pattern|$' file | less -r
egrep --color=always 'pattern|$' file | less -r
正如grep -E '|pattern'已经被建议的那样,只是想澄清一下,它也可以突出显示整行。
例如:tail -f somelog | grep——color -E '| \[2\]。*'(特别是-E '|部分):
您也可以创建别名。在你的.bashrc(或osx上的.bash_profile)中添加这个函数
function grepe {
grep --color -E "$1|$" $2
}
你现在可以这样使用别名:"ifconfig | grepe inet"或"grepe css index.html"。
(PS:别忘了源~/。在当前会话上重新加载Bashrc)