Email or username:

Password:

Forgot your password?
Darius Kazemi

grep -5 "foo" *.txt

will search for lines containing "foo" in *.txt files in your directory ... and also provide the 5 lines before and after each match for context! The number can be any number between 1 and 9.

If you need more than 9 lines you can do:

grep -C 20 "foo" *.txt

There are also -A and -B options that let you specify after-lines and before-lines.

5 comments | Expand all CWs
Alexander Bochmann

@darius I knew about after/before/context, but wasn't aware you could just use a number...

colin mitchell

@darius i use this to search codebases for methods called near another method when i can remember some details about one call but not the other

JauntyWunderKind

@darius i've used -A and -B for years but i didn't know about -C or -5. nice free win there, sweet.

Soh Kam Yung

@darius For more complexity, I usually combine find and xargs with grep:

find . -iname "*.txt" -print0 | xargs -0 grep -5 "foo"

with params, you can use "find" to include/exclude files/directories (e.g. ignore ".git", or softlinks) recursively.

"-print0 | xargs 0" turns all filenames into NULL terminated strings parameters, letting you search filenames with embedded spaces.

Yeah, with power comes complexity. 🙂

external quantum efficiency

@darius the --color option is extra nice with context too.

If you want both color and less(1), you have to do this goop:

grep --color=always ... | less -R

Go Up