Using find and grep to print lines before and after what you’re searching for

A cool thing about the Unix/Linux grep command is that you can show lines before and after a pattern match with the -B and -A options. As an example, I just used this combination of find and grep to search for all Scala files under the current directory that contain the string null. This command prints five lines before and after each null line in each file:

$ find . -type f -name "*.scala" -exec grep -B5 -A5 null {} \;

That’s good stuff, but it prints a really long list of lines, and I can’t tell the output of one file from another. To fix this, I put the following code in a file named helper.sh, and made it executable:

grep -B5 -A5 null $1 && echo "\n----- previous code from ($1) -----"

Now I run this find command:

$ find . -type f -name "*.scala" -exec ./helper {} \;

it results in output like this:

-----
      s <- c.supplier
    } yield (c, s)).groupBy(_._2.id).map {
      case (_, q) => (q.map(_._2.name).min.get, q.length)
    }
    // .get is needed because SLICK cannot enforce statically that
    // the supplier is always available (being a non-nullable foreign key),
    // thus wrapping it in an Option
    q4 foreach { case (name, count) =>
      println("  " + name + ": " + count)
    }
  }

----- previous code from (./slick-examples/src/main/scala/scala/slick/examples/lifted/FirstExample.scala) -----
    </html>
  }

  notFound {
    // remove content type in case it was set through an action
    contentType = null 
    // Try to render a ScalateTemplate if no route matched
    findTemplate(requestPath) map { path =>
      contentType = "text/html"
      layoutTemplate(path)
    } orElse serveStaticResource() getOrElse resourceNotFound() 

----- previous code from (./test1/src/main/scala/com/alvinalexander/test1/TestServlet1.scala) -----

This command prints five lines before and after the string/pattern null in all *.scala files under my current directory. There might be better ways to do this, but this makes me happy. ;)