Last Updated: February 25, 2016
· sensae

Grab multiple lines with grep

Sometimes it's useful to grab a couple lines before or after what you're searching for with grep. As an example, I was looking for a git viewer for my ArchLinux machine. A first attempt might look something like

pacman -Ss git | grep view

The problem is that this will probably match 'view' in the one-line package description, it's less likely that 'view' is part of the actual package name. The flags -B and -A will let you grab extra lines, either before or after the match. The even terser flag - will print whichever number of extra lines both before and after the match.

Taking advantage of these grep flags, a more precise command might look like this:

λ ~/ pacman -Ss git | grep view -B 1
community/giggle 0.7-1 [installed]
    Git repository viewer
community/gitg 0.2.5-1
    A GIT repository viewer based on GTK+
community/qgit 2.3-4
    A GIT GUI viewer built on Qt/C++

This makes the output nicer and easier to parse. Getting more comfortable with core GNU tools such as grep, sed or awk can give you a tremendous amount of power when it comes to parsing and managing streams of text.