【问题标题】:Search regex pattern with PowerShell and output filename使用 PowerShell 搜索正则表达式模式并输出文件名
【发布时间】:2020-04-02 19:32:38
【问题描述】:
$input_path = "d:\txt\*.txt"
$output_file = 'd:\out.txt'
$regex = "\w* (\w\.? )?\w* (was )?[B|b]orn .{100}"
select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file

Powershell 初学者在这里。我希望它遍历特定​​目录中的所有文件,搜索特定的正则表达式模式并将结果输出到文件中。到目前为止,我已经设法解决了上述问题。我怎样才能让它也输出每个匹配的文件名?

【问题讨论】:

    标签: regex powershell select-string


    【解决方案1】:

    您可以执行以下操作:

    $input_path = "d:\txt\*.txt"
    $output_file = 'd:\out.txt'
    $regex = "\w* (\w\.? )?\w* (was )?[B|b]orn .{100}"
    Select-String -Path $input_path -Pattern $regex -AllMatches | Foreach-Object {
        $currentMatches = $_
        $_.Matches | Foreach-Object { $_.Value,$currentMatches.Filename -join ' | ' } |
            Add-Content $output_file
    }
    

    说明:

    Select-String 将返回MatchInfo 对象的集合。这些对象中的每一个都有一个Filename 属性,该属性仅包含包含匹配项的文件的文件名。由于单个文件中可能有多个匹配项(由于 -AllMatches),因此有必要遍历 MatchInfo 对象中的每个匹配项。

    -join 运算符使用定义的字符串分隔符连接集合中的所有项目。

    【讨论】:

      【解决方案2】:

      所以对于你的最后一行,使用:

      # put matches into var
      $matches = Select-String -Path $input_path -Pattern $regex -AllMatches
      # write out to file
      foreach ($m in $matches) { $m.Filename | Out-File $output_file -Append -NoClobber }
      

      【讨论】:

      • 谢谢机器人科学!我暂时避免使用别名。使用你的线路,我还是没有得到文件名。不知道我在这里做错了什么。
      • 啊,你想要文件名,我更新了我的答案。希望这对您更有效。
      • 是的,我试图获得类似Stphn Lastname was born in 1995 xyz | 1.txt Robot Science was born in 1996 xyz | 2.txt
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多