【问题标题】:Group-Object by numbers dynamically Powershell按数字动态分组对象Powershell
【发布时间】:2020-06-06 02:13:17
【问题描述】:

我得到了一个具有以下模式的文件:

10:15:16:290 53123
10:15:16:290 ra-agi Trace: Sending Query Request message to application gateway host.     10:15:16:290 ra-agi Trace:     ApplicationGatewayID = 5001  10:15:16:290 ra-agi Trace:     InvokeID =             5456787 
10:15:16:493 5456787
10:15:16:306 ra-agi Trace: Sending Query Request message to application gateway host.     10:15:16:306 ra-agi Trace:     ApplicationGatewayID = 5000  10:15:16:306 ra-agi Trace:     InvokeID =             132 
10:15:16:337 132
10:15:16:509 54565
10:15:16:337 ra-agi Trace: Sending Query Request message to application gateway host.     10:15:16:337 ra-agi Trace:     ApplicationGatewayID = 5001  10:15:16:337 ra-agi Trace:     InvokeID =             54565 
10:15:16:400 5456512
10:15:16:384 ra-agi Trace: Sending Query Request message to application gateway host.     10:15:16:384 ra-agi Trace:     ApplicationGatewayID = 5000  10:15:16:384 ra-agi Trace:     InvokeID =             5456512 
10:15:16:603 5
10:15:16:400 ra-agi Trace: Sending Query Request message to application gateway host.     10:15:16:400 ra-agi Trace:     ApplicationGatewayID = 5001  10:15:16:400 ra-agi Trace:     InvokeID =             5 
10:15:16:493 ra-agi Trace: Sending Query Request message to application gateway host.     10:15:16:493 ra-agi Trace:     ApplicationGatewayID = 5000  10:15:16:493 ra-agi Trace:     InvokeID =             3124 
10:15:16:509 3124
10:15:16:509 ra-agi Trace: Sending Query Request message to application gateway host.     10:15:16:509 ra-agi Trace:     ApplicationGatewayID = 5000  10:15:16:509 ra-agi Trace:     InvokeID =             95787812 
10:15:16:525 95787812
10:15:16:509 ra-agi Trace: Sending Query Request message to application gateway host.     10:15:16:509 ra-agi Trace:     ApplicationGatewayID = 5001  10:15:16:509 ra-agi Trace:     InvokeID =             9578781 
10:15:16:728 9578781
10:15:16:712 62

使用我的代码,我尝试使用以下代码按数字对短行进行排序:

$result = [System.IO.File]::ReadLines($file).Trim() |
Group-Object @{Expression = { [int] $_.Substring($_.Length - 8)} } | # group by InvokeID (last 8 characters of the shortline) 
Where-Object { $_.Count -eq 2 } | # select only groups with two items in it (one long and one short line)

我的问题是数字并不总是具有相同的长度。我怎样才能使它动态?我得到了从 1 位到 8 位的数字。

【问题讨论】:

    标签: powershell grouping group-object


    【解决方案1】:

    使用带有正则表达式的 -replace 运算符来删除除尾随连续数字之外的所有内容:

    ... |Group-Object { ($_ -replace '^.*?(\d+)$', '$1') -as [int] }
    

    【讨论】:

      猜你喜欢
      • 2010-09-20
      • 1970-01-01
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 2013-02-02
      相关资源
      最近更新 更多