output neighbouring lines with line numbers while grepping

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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You can use GNU grep‘s Context Line Control, from man grep:

-A NUM, –after-context=NUM
Print NUM lines of trailing context after matching lines. Places a line containing a group separator (–) between contiguous groups of
matches. With the -o or –only-matching option, this has no effect and a warning is given.

-B NUM, –before-context=NUM
Print NUM lines of leading context before matching lines. Places a line containing a group separator (–) between contiguous groups of
matches. With the -o or –only-matching option, this has no effect and a warning is given.

If you require an equal number of lines either side, you can use a single context number:

-C NUM, -NUM, –context=NUM
Print NUM lines of output context. Places a line containing a group separator (–) between contiguous groups of matches. With the -o or
–only-matching option, this has no effect and a warning is given.

When combined with the -n flag (--line-number), you have numbered matches with surrounding context.

In your example:

grep -n -C1 download

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply