【问题标题】:How to "grep" in PowerShell and also show surrounding lines/context?如何在 PowerShell 中“grep”并显示周围的行/上下文?
【发布时间】:2020-09-25 06:42:16
【问题描述】:

Powershell cmd 的“上下文行控制”设置是什么:findstr 或什么是替代 Powershell cmd,它可以让我在某些输出中找到字符串并方便我打印周围的行?

在 GNU/Linux 上我会这样做:grep -A 5 -B 5 somestring file.txt

下面的命令搜索字符串“four”,但要求 grep 在找到的行上方显示 1 行,在找到的包含字符串的行下方显示 2 行。

$ grep -A 2 -B 1 four tmp.text
three
four
five
six
$ cat tmp.text
one
two
three
four
five
six
seven

谢谢

【问题讨论】:

  • 我添加了一个示例来说明我在寻找什么。
  • 看看Select-String。您应该阅读完整的帮助,包括示例以了解如何使用它。
  • 我喜欢你在他发布答案后立即回答的方式。

标签: powershell cmd command full-text-search command-line-arguments


【解决方案1】:

我在这里找到了答案:https://communary.net/2014/11/10/grep-the-powershell-way/

您可以像这样搜索示例文件:

PS C:\Users\dan> Select-String four .\tmp.txt -Context 1,3

  tmp.txt:3:three
> tmp.txt:4:four
  tmp.txt:5:five
  tmp.txt:6:six
  tmp.txt:7:seven

【讨论】:

猜你喜欢
  • 2010-09-05
  • 1970-01-01
  • 2011-09-11
  • 2010-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多