gpt4 book ai didi

powershell - 通过正则表达式从行中提取特定的多个字符串

转载 作者:行者123 更新时间:2023-12-03 22:31:01 25 4
gpt4 key购买 nike

我一直在尝试使用 PowerShell 从 .txt 文件内的多行中提取某些值。我有一个包含所有备份的巨大文件,并试图提取所有这些行。

文本文件:

Backup-ID:           hostname01
Policy: VM_weekly
Primary Copy: 23
Expires: 1/5/2024 3:19:13 AM
Type: 4


Copy Number: 2
Fragment Size (KB): 6188832
Expires: 1/5/2024 3:19:13 AM
MediaID: XXX122
TestID: 1222
Block: 33


Copy Number: 3
Fragment Size (KB): 6188832
Expires: 1/5/2024 3:19:13 AM
MediaID: XXX134
TestID: 223
Block: 22
Duplicate: N



Backup-ID: hostname02
Policy: VM_weekly2
Primary Copy: 24
Expires: 1/5/2024 3:19:13 AM
Type: 2


Copy Number: 2
Fragment Size (KB): 6188832
Expires: 1/5/2024 3:19:13 AM
MediaID: XXX244
Comp: BBB
Block: 45
Duplicate: N


Copy Number: 3
Fragment Size (KB): 6188832
Expires: 1/5/2024 3:19:13 AM
MediaID: XXX199
Comp: AA
Block: 334

Copy Number: 4
Fragment Size (KB): 6188832
Expires: 1/5/2024 3:19:13 AM
MediaID: XXX177

到目前为止我有代码:

Get-Content C:\test.txt | Select-String -Pattern 'Backup-ID: ' ,'Policy: ' ,'Primary Copy: ' ,'Expires:  ' ,'Copy Number: ' , 'Fragment Size ' ,'Expires: ' , 'MediaID:'

这就是我想要的:

hostname01,VM_weekly,23,6188832,1/5/2024 3:19:13 AM,XXX122,3,6188832,1/5/2024 3:19:13 AM,XXX134
hostname02,VM_weekly2,24,1/5/2024 3:19:13 AM,2,6188832,1/5/2024 3:19:13 AM,XXX244,3,6188832,1/5/2024 3:19:13 AM,XXX199,4,6188832,1/5/2024 3:19:13 AM,XXX177

最佳答案

这是我的老式方法:

$line = ''
Get-Content C:\test.txt |
Select-String -Pattern 'Backup-ID: ' ,'Policy: ' ,'Primary Copy: ' ,'Expires: ' ,'Copy Number: ' , 'Fragment Size ' ,'Expires: ' , 'MediaID:' |
ForEach-Object {
$aux = $_ -split ':',2 # only 2 substrings
if ($aux[0] -eq 'Backup-ID') {
if ( $line -ne '' ) { $line } # Write-Output (current line)
$line = $aux[1].Trim()
} else {
$line += ',' + $aux[1].Trim()
}
}
$line # Write-Output (last line)

输出:

D:\PShell\SO\54921319.ps1
hostname01,VM_weekly,23,1/5/2024 3:19:13 AM,2,6188832,1/5/2024 3:19:13 AM,XXX122,3,6188832,1/5/2024 3:19:13 AM,XXX134
hostname02,VM_weekly2,24,1/5/2024 3:19:13 AM,2,6188832,1/5/2024 3:19:13 AM,XXX244,3,6188832,1/5/2024 3:19:13 AM,XXX199,4,6188832,1/5/2024 3:19:13 AM,XXX177

编辑:…我需要导出 CSV 文件…

$xArr = D:\PShell\SO\54921319.ps1
$xCsv = $xArr | ConvertFrom-Csv -Header $(1..30|%{"a$_"})
$xcsv | Export-Csv -NoTypeInformation -Path c:\temp\result.csv

当然,你可以计算

  • -Header $(1..30|%{"a$_"}) 的实际上限,而不是估计 30例如为 ($xArr | % {$_.Split(',').Count}|Measure-Object -Maximum).Maximum,
  • 甚至计算一些人类可读 header (考虑到给定Backup-ID内每个Copy Number的一些属性的重复名称)

关于powershell - 通过正则表达式从行中提取特定的多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54921319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com