[search] grep a file, but show several surrounding lines?

I would like to grep for a string, but also show the preceding five lines and the following five lines as well as the matched line. How would I be able to do this?

This question is related to search logging grep command-line-interface

The answer is


If you search code often, AG the silver searcher is much more efficient (ie faster) than grep.

You show context lines by using -C option.

Eg:

ag -C 3 "foo" myFile

line 1
line 2
line 3
line that has "foo"
line 5
line 6
line 7

I use to do the compact way

grep -5 string file

That is the equivalent of

grep -A 5 -B 5 string file

Search for "17655" in "/some/file.txt" showing 10 lines context before and after (using Awk), output preceded with line number followed by a colon. Use this on Solaris when 'grep' does not support the "-[ACB]" options.

awk '

/17655/ {
        for (i = (b + 1) % 10; i != b; i = (i + 1) % 10) {
                print before[i]
        }
        print (NR ":" ($0))
        a = 10
}

a-- > 0 {
        print (NR ":" ($0))
}

{
        before[b] = (NR ":" ($0))
        b = (b + 1) % 10
}' /some/file.txt;

ack works with similar arguments as grep, and accepts -C. But it's usually better for searching through code.


ripgrep

If you care about the performance, use ripgrep which has similar syntax to grep, e.g.

rg -C5 "pattern" .

-C, --context NUM - Show NUM lines before and after each match.

There are also parameters such as -A/--after-context and -B/--before-context.

The tool is built on top of Rust's regex engine which makes it very efficient on the large data.


grep astring myfile -A 5 -B 5

That will grep "myfile" for "astring", and show 5 lines before and after each match


$ grep thestring thefile -5

-5 gets you 5 lines above and below the match 'thestring' is equivalent to -C 5 or -A 5 -B 5.


Use grep

$ grep --help | grep -i context
Context control:
  -B, --before-context=NUM  print NUM lines of leading context
  -A, --after-context=NUM   print NUM lines of trailing context
  -C, --context=NUM         print NUM lines of output context
  -NUM                      same as --context=NUM

-A and -B will work, as will -C n (for n lines of context), or just -n (for n lines of context... as long as n is 1 to 9).


Grep has an option called Context Line Control, you can use the --context in that, simply,

| grep -C 5

or

| grep -5

Should do the trick


You can use option -A (after) and -B (before) in your grep command try grep -nri -A 5 -B 5 .


I normally use

grep searchstring file -C n # n for number of lines of context up and down

Many of the tools like grep also have really great man files too. I find myself referring to grep's man page a lot because there is so much you can do with it.

man grep

Many GNU tools also have an info page that may have more useful information in addition to the man page.

info grep

Here is the @Ygor solution in awk

awk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=3 a=3 s="pattern" myfile

Note: Replace a and b variables with number of lines before and after.

It's especially useful for system which doesn't support grep's -A, -B and -C parameters.


Find a file by name in Visual Studio Code Search all the occurrences of a string in the entire project in Android Studio Java List.contains(Object with field value equal to x) Trigger an action after selection select2 How can I search for a commit message on GitHub? SQL search multiple values in same field Find a string by searching all tables in SQL Server Management Studio 2008 Search File And Find Exact Match And Print Line? Java - Search for files in a directory How to put a delay on AngularJS instant search?

Examples related to logging

How to redirect docker container logs to a single file? Console logging for react? Hide strange unwanted Xcode logs Where are logs located? Retrieve last 100 lines logs Spring Boot - How to log all requests and responses with exceptions in single place? How do I get logs from all pods of a Kubernetes replication controller? Where is the Docker daemon log? How to log SQL statements in Spring Boot? How to do logging in React Native?

Examples related to grep

grep's at sign caught as whitespace cat, grep and cut - translated to python How to suppress binary file matching results in grep Linux find and grep command together Filtering JSON array using jQuery grep() Linux Script to check if process is running and act on the result grep without showing path/file:line How do you grep a file and get the next 5 lines How to grep, excluding some patterns? Fast way of finding lines in one file that are not in another?

Examples related to command-line-interface

How to change port number in vue-cli project How to change the project in GCP using CLI commands Switch php versions on commandline ubuntu 16.04 Find nginx version? Laravel 5 – Clear Cache in Shared Hosting Server How to open Atom editor from command line in OS X? Is there a way to continue broken scp (secure copy) command process in Linux? Execute a command line binary with Node.js Change working directory in my current shell context when running Node script Is there a way to follow redirects with command line cURL?