Grep 上下文
Grep是一个非常强大的工具,用于在文件中查找内容。我经常用它来扫描Drupal代码库中的插件或扫描CSV或日志文件中的数据。
例如,要扫描Drupal核心目录中以用户为中心的ViewsFilter插件,请使用此命令(假设您相对于核心目录)。
grep"@ViewsFilter(\"user"-rcore
此处的-r标志递归扫描“核心”目录。此命令返回以下输出。
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")
在查看日志文件时,我做的一件事是查看围绕从grep返回的字符串的上下文。这是匹配线上方或下方的线。Grep有几个内置标志允许这样做。
这是文档的摘录。
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.
继续上面的示例,如果您想在匹配后查看上下文3行,您可以使用-A标志,如下所示。
grep"@ViewsFilter(\"user"-rcore-A3
如果您想在比赛前查看上下文3行,您可以像这样使用-B标志。
grep"@ViewsFilter(\"user"-rcore-B3
如果您想查看比赛前3行和比赛后3行的上下文,请使用-C标志,如下所示。
grep"@ViewsFilter(\"user"-rcore-C3
记住这一点的简单方法是-A标志,如果用于AFTER,则-B标志用于BEFORE,在典型的Unix幽默中,两者的组合是-C标志。