bash grep like 命令来查找匹配的线和邻域线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7381480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:45:41  来源:igfitidea点击:

grep like command to find matching lines plus neighbourhood lines

bashgrep

提问by ztank1013

grepcommand is really powerful and I use it a lot.

grep命令非常强大,我经常使用它。

Sometime I have the necessity to find something with grep looking inside many many files to find the string I barely remember helping myself with -i(ignore case) option, -r(recursive) and also -v(exclude).

有时我需要用 grep 在许多文件中查找一些东西来找到我几乎不记得使用-i(忽略大小写)选项、-r(递归)和-v(排除)帮助自己的字符串。

But what I really need is to have a special output from grep which highlight the matching line(s) plus the neighbourhood lines(given the matching line I'd like to see, let's say, the 2 preceding and the 2 subsequent lines).

但我真正需要的是 grep 的特殊输出,它突出显示匹配线和邻域线(给定我想看到的匹配线,假设是前 2 行和后 2 行)。

Is there a way to get this result using bash?

有没有办法使用 bash 获得这个结果?

采纳答案by ennuikiller

most greps allow the "context" flag making it a bit more readable:

大多数 grep 允许“上下文”标志,使其更具可读性:

grep --context=3 foo myfile.txt

回答by chotchki

Grepitself will do this

Grep本身会这样做

grep -A 2 -B 2 foo myfile.txt

回答by Kristjan Adojaan

You can omit -C

你可以省略 -C

grep -2 foo myfile.txt

is equal to

等于

grep -C 2 foo myfile.txt