Powershell 从一个列表中过滤出另一个列表

标签 powershell filter

<updated, added Santiago Squarzon suggest information>

我有两个列表,我从 csv 中提取它们,但两个列表中的每一个都只有一列。
这是我在脚本中拉入列表的方式

$orginal_list = Get-Content -Path .\random-word-350k-wo-quotes.txt
$filter_words = Get-Content -Path .\no_go_words.txt

但是,为了简单起见,我将在下面的代码示例中使用类型列表。

在这个例子中,$original_list 可以重复一些单词。 我想过滤掉 $original_list$filter_words 列表中的所有单词。

然后将过滤后的列表添加到变量$filtered_list
在此示例中,$filtered_list 中只会包含 "dirt","turtle"
我知道我在下面减去两者的那一行行不通,它在那里作为占位符,因为我不知道用什么来获得结果。

值得注意的是,为 $original_list 提供数据的 csv 文件可能有 300,000 或更多行,而 $filter_words 可能有 数百行 行。所以希望它尽可能高效。
过滤不区分大小写

$orginal_list = "yellow","blue","yellow","dirt","blue","yellow","turtle","dirt"
$filter_words = "yellow","blue","green","harsh"

$filtered_list = $orginal_list - $filter_words

$filtered_list

dirt
turtle

最佳答案

使用System.Collections.Generic.HashSet`1及其 .ExceptWith()方法:

# Note: if possible, declare the lists as [string[]] arrays to begin with.
#       Otherwise, use a [string[]] cast im the method calls below, which,
#       however, creates a duplicate array on the fly.
[string[]] $orginal_list = "yellow","blue","yellow","dirt","blue","yellow","turtle","dirt"
[string[]] $filter_words = "yellow","blue","green","harsh"

# Create a hash set based on the strings in $orginal_list,
# with case-insensitive lookups.
$hsOrig = [System.Collections.Generic.HashSet[string]]::new(
  $orginal_list,
  [System.StringComparer]::CurrentCultureIgnoreCase
)

# Reduce it to those strings not present in $filter_words, in-place.
$hsOrig.ExceptWith($filter_words)

# Convert the filtered hash set to an array.
[string[]] $filtered_list = [string[]]::new($hsOrig.Count)
$hsOrig.CopyTo($filtered_list)

# Output the result
$filtered_list

以上结果:

dirt
turtle

要同时加快读取输入文件的速度,请使用以下命令:

# Note: System.IO.File]::ReadAllLines() returns a [string[]] instance.
$orginal_list = [System.IO.File]::ReadAllLines((Convert-Path .\random-word-350k-wo-quotes.txt))
$filter_words = [System.IO.File]::ReadAllLines((Convert-Path .\no_go_words.txt))

注意:

  • .NET 通常默认为(无 BOM)UTF-8;如果需要,将 [System.Text.Encoding] 实例作为第二个参数传递。

  • .NET 的工作目录。通常与 PowerShell 不同,因此在 .NET API 调用中始终建议使用完整 路径,这就是 Convert-Path电话确保。

关于Powershell 从一个列表中过滤出另一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72624314/

相关文章:

powershell - 检查 HTTP 端口是否在 Windows 上打开

java - 获取Windows Server中程序的Java/JVM路径

xml - 使用 Powershell 删除一组 XML 元素

powershell - 为虚拟机分配保留 IP

multithreading - 如何停止无限线程

mysql - 食谱数据库,按成分搜索

arrays - 来自一维数组的唯一值,无需迭代

go - 如何在查询路由器中使用多个参数

ios - 使用 Swift CoreData 进行动态过滤

java - 如何使用 grails 1.3.2 和插件 spring-security-core 1 实现自定义 FilterSecurityInterceptor?