Learn to Code by Making Art
Learn programming while your create computer art by copying code from my free guide.
https://splashofcode.com

Grep a Range of Lines

I was looking for a solution to grep through a file and return a range of lines. Although I didn't find exactly what I thought I wanted, I did find a workable solution.

In this case, I wanted to search through a file looking for the name of a car dealership (Cool Auto). Once it found that line, I wanted one line BEFORE the match and 1000 lines after the match (essentially the part of the log file that deals with this particular dealership).

The following command line will grep from x lines [before] the match through x lines [after] the match.

  grep "^Cool Auto" myfile.log -B1 -A1000 > cool.log

“^Cool Auto” is a regular expression. The carrot (^) means the start of a line. So, the quoted text means to find the line that starts with the dealer name Cool Auto. The -B1 gives us 1 line before the match. The -A1000 gives us 1000 lines after the match. Finally, I redirect the output using > to the file cool.log.

Learn to Code by Making Art
Learn programming while your create computer art by copying code from my free guide.
https://splashofcode.com
comments powered by Disqus
linux/grep_a_range_of_lines.txt · Last modified: 2010/04/27 15:38 by Joel Dare