Grep Context

27th June 2020

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.

  1. core/modules/user/src/Plugin/views/filter/Roles.php: * @ViewsFilter("user_roles")
  2. core/modules/user/src/Plugin/views/filter/Permissions.php: * @ViewsFilter("user_permissions")
  3. core/modules/user/src/Plugin/views/filter/Current.php: * @ViewsFilter("user_current")
  4. 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.

  1. Context Line Control
  2. -A NUM, --after-context=NUM
  3. Print NUM lines of trailing context after matching lines.
  4. Places a line containing a group separator (--) between
  5. contiguous groups of matches. With the -o or --only-matching
  6. option, this has no effect and a warning is given.
  7.  
  8. -B NUM, --before-context=NUM
  9. Print NUM lines of leading context before matching lines.
  10. Places a line containing a group separator (--) between
  11. contiguous groups of matches. With the -o or --only-matching
  12. option, this has no effect and a warning is given.
  13.  
  14. -C NUM, -NUM, --context=NUM
  15. Print NUM lines of output context. Places a line containing a
  16. group separator (--) between contiguous groups of matches. With
  17. the -o or --only-matching option, this has no effect and a
  18. 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.