Grep Context

27th June 2020 - 3 minutes read time

Grep is a really powerful tool for finding things in files. I often use it to scan for plugins in the Drupal codebase or to scan through a CSV or log file for data.

For example, to scan for user centric ViewsFilter plugins in the Drupal core directory use this command (assuming you are relative to the core directory).

grep "@ViewsFilter(\"user" -r core

The -r flag here recursively scans the 'core' directory. This command returns the following output.

core/modules/user/src/Plugin/views/filter/Roles.php: * @ViewsFilter("user_roles")
core/modules/user/src/Plugin/views/filter/Permissions.php: * @ViewsFilter("user_permissions")
core/modules/user/src/Plugin/views/filter/Current.php: * @ViewsFilter("user_current")
core/modules/user/src/Plugin/views/filter/Name.php: * @ViewsFilter("user_name")

One thing I do when looking at log files is to look at the context surrounding the returned strings from grep. This is the lines above or below the matched lines. Grep has a couple of built in flags that allow this.

Here is an excerpt from the documentation.


   Context Line Control
       -A NUM, --after-context=NUM
              Print NUM  lines  of  trailing  context  after  matching  lines.
              Places   a  line  containing  a  group  separator  (--)  between
              contiguous groups of matches.  With the  -o  or  --only-matching
              option, this has no effect and a warning is given.

       -B NUM, --before-context=NUM
              Print  NUM  lines  of  leading  context  before  matching lines.
              Places  a  line  containing  a  group  separator  (--)   between
              contiguous  groups  of  matches.  With the -o or --only-matching
              option, this has no effect and a warning is given.

       -C NUM, -NUM, --context=NUM
              Print NUM lines of output context.  Places a line  containing  a
              group separator (--) between contiguous groups of matches.  With
              the -o or --only-matching option,  this  has  no  effect  and  a
              warning is given.

Carrying on from the example above, if you want to look at the context 3 lines after your match you would use the -A flag like this.

grep "@ViewsFilter(\"user" -r core -A 3

If you want to look at the context 3 lines before your match you would use the -B flag like this.

grep "@ViewsFilter(\"user" -r core -B 3

If you want to look at the context 3 lines before and 3 lines after your match use the -C flag like this.

grep "@ViewsFilter(\"user" -r core -C 3

The easy way to remember this is the -A flag if for AFTER, the -B flag is for BEFORE, and in typical Unix humour, the combination of the two is the -C flag.

Add new comment

The content of this field is kept private and will not be shown publicly.