我正在寻找PowerShell等价于grep——file=filename。如果你不知道grep, filename是一个文本文件,其中每一行都有一个你想要匹配的正则表达式模式。

也许我遗漏了一些明显的东西,但是Select-String似乎没有这个选项。


当前回答

Select-String中的-Pattern参数支持模式数组。所以你要找的是

Get-Content .\doc.txt | Select-String -Pattern (Get-Content .\regex.txt)

它通过使用regex.txt中的每个regex(每行一个)来搜索文本文件doc.txt

其他回答

但是select-String似乎没有这个选项。

正确的。PowerShell不是*nix shell工具集的克隆。

然而,自己建造这样的东西并不难:

$regexes = Get-Content RegexFile.txt | 
           Foreach-Object { new-object System.Text.RegularExpressions.Regex $_ }

$fileList | Get-Content | Where-Object {
  foreach ($r in $regexes) {
    if ($r.IsMatch($_)) {
      $true
      break
    }
  }
  $false
}

Select-String中的-Pattern参数支持模式数组。所以你要找的是

Get-Content .\doc.txt | Select-String -Pattern (Get-Content .\regex.txt)

它通过使用regex.txt中的每个regex(每行一个)来搜索文本文件doc.txt

PS) new-alias grep findstr
PS) C:\WINDOWS> ls | grep -I -N exe

105:-a---        2006-11-02     13:34      49680 twunk_16.exe
106:-a---        2006-11-02     13:34      31232 twunk_32.exe
109:-a---        2006-09-18     23:43     256192 winhelp.exe
110:-a---        2006-11-02     10:45       9216 winhlp32.exe

PS) grep /?

我不熟悉grep,但选择字符串你可以做:

Get-ChildItem filename.txt | Select-String -Pattern <regexPattern>

你也可以使用Get-Content:

(Get-Content filename.txt) -match 'pattern'

所以我在这个链接上找到了一个很好的答案: https://www.thomasmaurer.ch/2011/03/powershell-search-for-string-or-grep-for-powershell/

但本质上是:

Select-String -Path "C:\file\Path\*.txt" -Pattern "^Enter REGEX Here$"

这在PowerShell的一行中提供了目录文件搜索(*或者您可以只指定一个文件)和文件内容搜索,非常类似于grep。输出将类似于:

doc.txt:31: Enter REGEX Here
HelloWorld.txt:13: Enter REGEX Here