2

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?

4

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.