Is there a way to output the neighbouring lines along with the line numbers while grepping the contents of a file? I'm trying to get outputs of the form:
$ ~/myscript.sh download file # 'download' being the pattern here
121: # and downloads with wget/curl, whichever is available.
122: download_file () {
123: if which wget &>/dev/null; then
----------
356: # Since the prerequisites are already installed, we may proceed
357: download_urls=("http://example.com/foo/bar.bz2"
358: "http://d1.example.com/xyz/abc.tar.gz"
Of course, I know that I can get grep my pattern with the -n
option and show some of the neighbouring lines from the obtained line number (say, by using any of the methods here), but is there a better way to do this?
Best Answer
You can use GNU
grep
's Context Line Control, fromman grep
:If you require an equal number of lines either side, you can use a single context number:
When combined with the
-n
flag (--line-number
), you have numbered matches with surrounding context.In your example: