【问题标题】:Split pattern output by spaces in PowershellPowershell中的空格分割模式输出
【发布时间】:2019-05-22 23:24:09
【问题描述】:

我需要提取匹配模式后返回的字符串的第三列。 它还需要是单行的

文件包含如下数据:

f5834eab44ff bfd0bc8498d8 1557718920
dc8087c38a0d a72e89879030 1557691221
e6d7aaf6d76b caf6cd0ef68c 1557543565

现在它匹配模式并返回该行。 但我无法将其拆分为空格,因此我可以获得第 3 列(索引 2)。

    select-string -Path $hashlistfile -Pattern 'dc8087c38a0d') | $_.Split(" ") | $_[2] 

输出应该是:

1557691221

【问题讨论】:

    标签: windows powershell split


    【解决方案1】:

    您可以从Select-String 生成的输出对象中获取Line 属性,将其拆分然后直接索引到String.Split() 的结果中:

    Select-String -Path $hashlistfile -Pattern dc8087c38a0d |ForEach-Object {
      $_.Line.Split(" ")[2]
    }
    

    【讨论】:

    • @elcool 您还缺少ForEach-Object... | $_.Split() 语法无效。
    【解决方案2】:

    您只能在具有脚本块选项“{ }”的 cmdlet 中使用“$_”。 Select-string 返回 MatchInfo 对象。

    (select-string dc8087c38a0d $hashlistfile).gettype()
    
    IsPublic IsSerial Name                                     BaseType
    -------- -------- ----                                     --------
    True     False    MatchInfo                                System.Object
    

    -split 运算符似乎更容易处理它。在您的示例中的模式之后有一个额外的括号 ')'。

    select-string dc8087c38a0d $hashlistfile | foreach { -split $_ | select -index 2 }
    
    1557691221
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      相关资源
      最近更新 更多