【问题标题】:Using Powershell to match a pattern on all occurrences in a text file使用 Powershell 匹配文本文件中所有出现的模式
【发布时间】:2020-07-23 10:38:35
【问题描述】:

我有一个文本文件,我正在使用 Powershell 列出以下模式中存在的名称

文件内容:

beta-clickstream-class="owner:"mike""
beta-clickstream-class="owner:"kelly""
beta-clickstream-class="owner:"sam""
beta-clickstream-class="owner:"joe""
beta-clickstream-class="owner:"john""
beta-clickstream-class="owner:"tam""

我正在寻找的输出

mike
kelly
sam
joe
john
tam

我使用的脚本是

$importPath = "test.txt"
$pattern = 'beta-clickstream-class="owner:"(.*?)""'
$string = Get-Content $importPath
$result = [regex]::match($string, $pattern).Groups[1].Value
$result

以上脚本仅列出文件中的名字。请指导我如何列出文件中的所有名称。

【问题讨论】:

  • 只要使用-replace --> $string -replace $pattern,'$1'

标签: regex powershell match


【解决方案1】:

Get-Content 返回字符串的数组,因此您必须在数组$string每个元素 上调用[regex]::match()

但是,-replace operator,正如AdminOfThings 所建议的那样,可以实现更简单的解决方案:

(Get-Content $importPath) -replace '.+owner:"([^&]+).+', '$1'

或者,您可以将文件读入一个单个的多行字符串,其中包含Get-Content -Raw,后跟[regex]::Matches()(多个匹配项),而不是[regex]::Match()(单个匹配项)。

【讨论】:

    猜你喜欢
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 2017-04-24
    • 2014-11-02
    • 2012-02-29
    • 1970-01-01
    相关资源
    最近更新 更多