【问题标题】:Powershell: Filter the contents of a file by an array of stringsPowershell:通过字符串数组过滤文件的内容
【发布时间】:2013-02-12 09:26:34
【问题描述】:

猜猜这个:

我有一个数据文本文件。我想读入它,并且只输出包含在搜索词数组中找到的任何字符串的行。

如果我只寻找一个字符串,我会这样做:

get-content afile | where { $_.Contains("TextI'mLookingFor") } | out-file FilteredContent.txt

现在,我只需要将“TextI'mLookingFor”作为一个字符串数组,其中如果 $_ 包含数组中的任何字符串,它就会通过管道传递到输出文件。

我该怎么做(顺便说一句,我是一名 c# 程序员,正在破解这个 powershell 脚本,所以如果有比使用 .Contains() 更好的方法来完成我的匹配,请提示我!)

【问题讨论】:

    标签: powershell


    【解决方案1】:

    试试Select-String。它允许一系列模式。例如:

    $p = @("this","is","a test")
    Get-Content '.\New Text Document.txt' | Select-String -Pattern $p -SimpleMatch | Set-Content FilteredContent.txt
    

    请注意,我使用了-SimpleMatch,以便Select-String 忽略特殊的正则表达式字符。如果你想在你的模式中使用正则表达式,只需删除它。

    对于单个模式,我可能会使用它,但您必须转义模式中的正则表达式字符:

    Get-Content '.\New Text Document.txt' | ? { $_ -match "a test" }
    

    Select-String 也是一个很好的单一模式的 cmdlet,它只是写了几个字符^^

    【讨论】:

      【解决方案2】:

      有什么帮助吗?

      $a_Search = @(
          "TextI'mLookingFor",
          "OtherTextI'mLookingFor",
          "MoreTextI'mLookingFor"
          )
      
      
      [regex] $a_regex = ‘(‘ + (($a_Search |foreach {[regex]::escape($_)}) –join “|”) + ‘)’
      
      (get-content afile) -match $a_regex 
      

      【讨论】:

      • 选择字符串可能是更好的选择,尤其是对于文件数据。
      • 刚刚运行了一个快速测试,-match 对大量代表的效果更好(大约比 select-string 快 15 倍)。
      • 感谢正则表达式变体 +1。由于简单,我给出了选择字符串响应的答案。
      • 除非我在一个非常繁忙的循环中这样做,否则我也会这样做。 :)
      【解决方案3】:

      没有正则表达式和可能的空格:

      $array = @("foo", "bar", "hello world")
      get-content afile | where { foreach($item in $array) { $_.contains($item) } } > FilteredContent.txt
      

      【讨论】:

        【解决方案4】:
        $a = @("foo","bar","baz")
        findstr ($a -join " ") afile > FilteredContent.txt
        

        【讨论】:

          猜你喜欢
          • 2022-07-04
          • 2022-09-23
          • 1970-01-01
          • 2014-07-04
          • 1970-01-01
          • 2022-01-13
          • 2015-03-24
          • 2014-11-20
          • 2019-05-02
          相关资源
          最近更新 更多