Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 275
Mark Harrison Avatar asked Aug 12 '08 17:08

Mark Harrison


People also ask

How do you grep with surrounding lines?

For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match. If you want the same number of lines before and after you can use -C num . This will show 3 lines before and 3 lines after.

How do you grep multiple lines after a match?

Use the -A argument to grep to specify how many lines beyond the match to output. And use -B n to grep lines before the match. And -C in grep to add lines both above and below the match!

How do you grep above and below?

grep's -A 1 option will give you one line after; -B 1 will give you one line before; and -C 1 combines both to give you one line both before and after, -1 does the same.

How do I grep all lines in a file?

To search multiple files with the grep command, insert the filenames you want to search, separated with a space character. The terminal prints the name of every file that contains the matching lines, and the actual lines that include the required string of characters. You can append as many filenames as needed.


2 Answers

For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match.

grep -B 3 -A 2 foo README.txt 

If you want the same number of lines before and after you can use -C num.

grep -C 3 foo README.txt 

This will show 3 lines before and 3 lines after.

like image 150
Pat Notz Avatar answered Oct 07 '22 05:10

Pat Notz


-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).

like image 36
Stu Avatar answered Oct 07 '22 06:10

Stu