Paragraph grep with perl

Here is a very quick and easy perl one-liner that I use fairly often. When I am working with data that is contextualized in chunks of paragraphs (such as Cassandra columnfamily info), I often want to quickly find a single paragraph for a specific piece of information. Here is how I go about doing that in perl:

my_output_command | perl -00 -ne 'm/ninja/ && print'

This results in any paragraph containing the word “ninja” to be printed. The way this works is by the magic of the -00 flag. This flag causes the perl line-separator variable($/) to be set to ‘\n\n’, resulting in the one-liner iterating over STDIN for each paragraph, instead of each line.

Share and Enjoy:
  • StumbleUpon
  • Facebook
  • Twitter
  • Reddit
    • Scott
    • April 16th, 2013

    Great example!
    How can it be modified to match only on a line which exactly matches ninja, rather than finding ninja anywhere in the line?
    Equivalent to ‘^ninja$’
    Thanks!

  1. No trackbacks yet.