$ignoreList = @("muzi","puzi")
$data = "
blabla aa 11
blabla bb 22
muzi aa 20
muzi bb aa
aaa aa 41
blabla aa 20
puzi aa 11
puzi bb 32
puzi cc 44"我需要创建新的数据,它保存除忽略列表中的所有数据外的所有数据。
#i can iterate the list and run a loop, get $str to be the item in the list and
#and then save each time
$data | where-object {$_ -notlike $str}我觉得有比每次迭代abd savubg列表更好的选择
发布于 2021-12-25 15:53:51
-like当时只能处理一个模式(通配符表达式)。
要在单个操作中匹配多个模式,有两个选项:
[regex]::Escape()来转义忽略的单词,以便逐字使用它们作为正则表达式的一部分(对于特定的搜索术语来说,这不是绝对必要的,因此在这种简单的情况下,您可以使用'^(?:{0})' -f ($ignoreList -join '|'));正则表达式的使用还允许您断言必须在每个字符串的开头找到每个忽略单词(^):$ignoreList = @("muzi","puzi")
# Create an *array* of sample lines.
$data = @'
blabla aa 11
blabla bb 22
muzi aa 20
muzi bb aa
aaa aa 41
blabla aa 20
puzi aa 11
puzi bb 32
puzi cc 44"
'@ -split '\r?\n'
# The programmatically created regex results in:
# '^(?:muzi|puzi)'
# The ?: part isn't strictly necessary, but makes the (...) group
# non-capturing, which prevents unnecessary work.
$data -notmatch ('^(?:{0})' -f ($ignoreList.ForEach({ [regex]::Escape($_) }) -join '|'))-SimpleMatch,这可能是字面搜索术语。由于使用管道,这种方法更简单,但速度更慢:# Note the need to use (...).Line to extract the matching strings.
# In PowerShell (Core) 7+ you could use -Raw instead.
($data | Select-String -Pattern $ignoreList -SimpleMatch -NotMatch).Linehttps://stackoverflow.com/questions/70478355
复制相似问题