代码之家  ›  专栏  ›  技术社区  ›  Dan

如何在PowerShell中“grep”并显示周围的行/上下文?

  •  1
  • Dan  · 技术社区  · 6 年前

    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
    

    谢谢

    0 回复  |  直到 6 年前
        1
  •  8
  •   Dan    6 年前

    我在这里找到了答案: 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
    
    推荐文章