string - 用于模式数组的 Powershell 搜索字符串

标签 string powershell design-patterns

在 Powershell 中,您将如何在文本文件中的每一行中搜索一组模式? Select-string 的模式可以接受一个数组,但如果找到数组中的任何字符串,它就会返回一个真值。如果在行中找到数组中的所有字符串,我需要它返回 true(或实际上是行)。谢谢。

最佳答案

为了将字符串数组与模式数组匹配,我相信您需要这样的东西:

$patterns = @( ... )

Get-Content sample.txt | % {
  $count = 0
  foreach ($p in $patterns) {
    if ($_ -match $p) { $count++ }
  }
  if ($count -eq $patterns.Length) { $_ }
}

或者像这样:
$patterns = @( ... )

$content = Get-Content sample.txt
foreach ( $line in $content ) {
  $count = @($patterns | ? { $line -match $_ }).Length
  if ( $count -eq $patterns.Length ) { $line }
}

关于string - 用于模式数组的 Powershell 搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15726184/

相关文章:

python - 是否可以将 for 循环中的值放入列表中?

powershell - Web浏览器控件中的Powershell UI自动化

javascript - 我如何使用 JavaScript 创建此 API 并分解方法

ruby - 数字到英文单词 ruby

将字符串样式从 Arduino 转换为 C 通用样式

powershell - 如何列出根目录下的 namespace ?

multithreading - 通过作业完成的 Powershell Throttle 多线程作业

c# - 首先使用 EF4 代码制作存储库类的最佳做法是什么?

C# - 将 UI 与业务代码分开

string - Excel VBA函数处理分隔符