Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
linux:grep_a_range_of_lines [2010/04/27 15:38]
Joel Dare
linux:grep_a_range_of_lines [2020/06/01 22:53] (current)
Line 1: Line 1:
 +====== 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//​.
comments powered by Disqus