【问题标题】:Powershell clean String data using words in a defined listPowershell使用定义列表中的单词清理字符串数据
【发布时间】:2022-01-25 09:46:58
【问题描述】:
$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 更好的选择

【问题讨论】:

  • $ignoreList.ForEach{ $Data = $Data -Replace $_ }; $Data
  • [1] 您将$Data thru 作为一个多行字符串发送。那是你要的吗?还是你想处理每一行? ///// [2] 你想删除单词...还是包含这些单词的行? ///// [3] 尝试使用-replace 和正则表达式或模式。类似ThingOne|2ndThing|YetAnotherThing.

标签: powershell


【解决方案1】:

-like当时只能处理一个模式(wildcard表达式)。

在单个操作中匹配多个模式,您有两种选择:

  • 使用基于regex-notmatch 运算符交替表达式(|),这需要您转义带有[regex]::Escape() 的忽略词,以便将它们逐字用作正则表达式的一部分(对于您的特定搜索词不是绝对必要的,因此在这种简单的情况下,您可以使用'^(?:{0})' -f ($ignoreList -join '|') );使用正则表达式还允许您断言必须在每个字符串的 start 处找到每个忽略词 (^):
$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 '|'))
  • Select-String cmdlet 与多个模式一起使用(尽管您也可以使用一个交替模式),如果添加 @987654333,这可能是文字搜索词@。由于使用了管道,这种方法更简单,但速度更慢:
# 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).Line

【讨论】:

    猜你喜欢
    • 2021-11-16
    • 2013-01-21
    • 2020-07-18
    • 1970-01-01
    • 2017-09-07
    • 2021-02-05
    • 2021-02-16
    • 2019-07-18
    • 1970-01-01
    相关资源
    最近更新 更多