[英]Extract multiple line text file to single line csv using Powershell
我有一项任务,但没有一种简单的方法可以将一些数据解析为正确的格式。 我拥有的文本文件采用以下格式
#N Last Name: Joe
#D First Name: Doe
#P Middle Name: A
Some Data:
#C ID Number: (1) 12345
#S Status: (1) Active
#N Last Name: Jane
#D First Name: Doee
#P Middle Name:
Some Data:
#C ID Number: (1) 11111
#S Status: (1) Active
ID Number: (2) 1231
Status: (2) Active
这是我试图使用的代码。
$A = Select-String -Pattern "#N" MYFILE.txt;
$B = Select-String -Pattern "#D" MYFILE.txt;
$C = Select-String -Pattern "#P" MYFILE.txt;
$D = Select-String -Pattern "#C" MYFILE.txt;
$E = Select-String -Pattern "#S" MYFILE.txt;
$wrapper = New-Object PSObject -Property @{ FirstColumn = $A; SecondColumn = $B; ThirdColumn = $C; FourthColumn = $D; FifthColumn = $E }
Export-Csv -InputObject $wrapper -Path .\output.csv -NoTypeInformation
这是我得到的结果
"SecondColumn","ThirdColumn","FifthColumn","FourthColumn","FirstColumn"
"System.Object[]","System.Object[]","System.Object[]","System.Object[]","System.Object[]"
我正在寻找的 output 是; #N,#D,#P,#C,#S
Joe, Doe, A, 12345, Active
Jane, Doee, , 11111, Active
非常感谢任何和所有帮助。
这是解析该数据块的另一种方法。 我更改了用户信息,以使发生的事情更加明显。 [咧嘴笑]
它能做什么...
#region/#endregion
块替换为对Get-Content -Raw
的调用。#
开头,然后是字母和最后一个空格的行switch
[PSCustomObject]
来保存值$Result
集合foreach
] 如果您想从 CSV 中删除引号,请不要。 [ grin ] 如果您必须冒险破坏 CSV,那么您可以使用Get-Content
从文件中加载行并将引号替换为空。
编码...
#region >>> fake reading in a text file as a single multiline string
# in real life, use "Get-Content -Raw"
$InStuff = @'
#N Last Name: ALast
#D First Name: AFirst
#P Middle Name: AMid
Some Data:
#C ID Number: (1) 11111
#S Status: (1) Active
#N Last Name: BLast
#D First Name: BFirst
#P Middle Name:
Some Data:
#C ID Number: (1) 22222
#S Status: (1) Active
ID Number: (2) 1231
Status: (2) Active
'@
#endregion >>> fake reading in a text file as a single multiline string
$BlockDelim = ([System.Environment]::NewLine) * 2
$Result = foreach ($Block in ($InStuff -split $BlockDelim))
{
# initialize stuff to $Null
# this handles non-matches [such as a missing middle name]
$FirstName = $MidName = $LastName = $IdNumber = $Status = $Null
# the "-match" filters for lines that start with a "#", a single letter, and a space
foreach ($Line in ($Block -split [System.Environment]::NewLine -match '^#\w '))
{
switch ($Line[1])
{
'N' {
$LastName = $Line.Split(':')[-1].Trim()
break
}
'D' {
$FirstName = $Line.Split(':')[-1].Trim()
break
}
'P' {
$MidName = $Line.Split(':')[-1].Trim()
break
}
'C' {
$IdNumber = $Line.Split(':')[-1].Trim().Split(' ')[-1].Trim()
break
}
'S' {
$Status = $Line.Split(':')[-1].Trim().Split(' ')[-1].Trim()
break
}
} # end >>> switch ($Line[1])
} # end >>> foreach ($Line in ($Block -split [System.Environment]::NewLine))
# create a custom object and send it out to the collection
[PSCustomObject]@{
FirstName = $FirstName
LastName = $LastName
MidName = $MidName
IdNumber = $IdNumber
Status = $Status
}
} # end >>> foreach ($Block in ($InStuff -split $BlockDelim))
# display on screen
$Result
# send to a CSV file
$Result |
Export-Csv -LiteralPath "$env:TEMP\Veebster_ParsedResult.csv" -NoTypeInformation
屏幕上的 output...
FirstName : AFirst
LastName : ALast
MidName : AMid
IdNumber : 11111
Status : Active
FirstName : BFirst
LastName : BLast
MidName :
IdNumber : 22222
Status : Active
CSV 文件的内容...
"FirstName","LastName","MidName","IdNumber","Status"
"AFirst","ALast","AMid","11111","Active"
"BFirst","BLast","","22222","Active"
请注意,没有错误检测或错误处理。 [咧嘴笑]
这是另一个建议。 我的建议是使用 ConvertFrom-String。
首先我们将制作一个模板,我在您的示例数据中占了垃圾两行。 我真的希望这是一个错字/副本。
$template = @'
#N Last Name {[string]Last*:last1}
#D First Name: {[string]First:first1}
#P Middle Name: {[string]Middle:A}
#C ID Number: (1) {[int]ID:11111}
#S Status: (1) {[string]Status:status1}
#N Last Name: {[string]Last*:Jane}
#D First Name: {[string]First:Doee}
#P Middle Name: {[string]Middle: \s}
#C ID Number: (1) {[int]ID:11111}
#S Status: (1) {[string]Status:Active}
{!Last*:ID Number: (2) 1231
Status: (2) Active}
'@
现在我们将该模板应用于您的数据。 首先我们将解析一个here-string。
@'
#N Last Name: Joe
#D First Name: Doe
#P Middle Name: A
Some Data:
#C ID Number: (1) 12345
#S Status: (1) Active
#N Last Name: Jane
#D First Name: Doee
#P Middle Name:
Some Data:
#C ID Number: (1) 11111
#S Status: (1) Active
ID Number: (2) 1231
Status: (2) Active
'@ | ConvertFrom-String -TemplateContent $template -OutVariable results
Output
Last : Joe
First : Doe
Middle : A
ID : 12345
Status : Active
Last : Jane
First : Doee
ID : 11111
Status : Active
现在我们可以构建我们的 object 以准备导出。
$results | foreach {
[pscustomobject]@{
FirstName = $_.first
LastName = $_.last
MidName = $_.middle
IdNumber = $_.id
Status = $_.status
}
} -OutVariable export
现在我们可以导出它了
$export | Export-Csv -Path .\output.csv -NoTypeInformation
这是 output.csv 中的内容
PS C:\> Get-Content .\output.csv
"FirstName","LastName","MidName","IdNumber","Status"
"Doe","Joe","A","12345","Active"
"Doee","Jane",,"11111","Active"
这是从文件中读取它的相同内容。
$template = @'
#N Last Name {[string]Last*:last1}
#D First Name: {[string]First:first1}
#P Middle Name: {[string]Middle:A}
#C ID Number: (1) {[int]ID:11111}
#S Status: (1) {[string]Status:status1}
#N Last Name: {[string]Last*:Jane}
#D First Name: {[string]First:Doee}
#P Middle Name: {[string]Middle: \s}
#C ID Number: (1) {[int]ID:11111}
#S Status: (1) {[string]Status:Active}
{!Last*:ID Number: (2) 1231
Status: (2) Active}
'@
get-content .\ndpcs.txt |
ConvertFrom-String -TemplateContent $template | foreach {
[pscustomobject]@{
FirstName = $_.first
LastName = $_.last
MidName = $_.middle
IdNumber = $_.id
Status = $_.status
}
} | Export-Csv -Path .\output.csv -NoTypeInformation
让我们仔细检查一下我们的 CSV 的内容以确定。
Get-Content .\output.csv
"FirstName","LastName","MidName","IdNumber","Status"
"Doe","Joe","A","12345","Active"
"Doee","Jane",,"11111","Active"
需要注意的几点:如果这之后的数据集具有不同的特征,则需要向模板中添加更多样本。 如果两个额外的行(ID 和状态)不应该在那里,只需删除模板的那部分。
我建议大家在制定逻辑/构建脚本时使用 -outvariable 参数,因为您可以看到 output 并同时分配给变量。
这会起作用,但它像罪一样丑陋。
# Get content from text file
$Txtfile = Get-Content "C:\temp\test.txt" -raw
# Add delimiter to split users
$Delimiter = "
"
$Users = $Txtfile -split $Delimiter
# Create an array list to add data to so it can be exported later.
$collectionVariable = New-Object System.Collections.ArrayList
ForEach($Grouping in $Users) {
$temp = New-Object System.Object
$temp | Add-Member -MemberType NoteProperty -Name "#N" -Value (([regex]::match($Grouping, '#N.*').value) -split " ")[-1]
$temp | Add-Member -MemberType NoteProperty -Name "#D" -Value (([regex]::match($Grouping, '#D.*').value) -split " ")[-1]
$temp | Add-Member -MemberType NoteProperty -Name "#P" -Value (([regex]::match($Grouping, '#P.*').value) -split " ")[-1]
$temp | Add-Member -MemberType NoteProperty -Name "#C" -Value (([regex]::match($Grouping, '#C.*').value) -split " ")[-1]
# This is [-2] due to new line at end of the groupings.
$temp | Add-Member -MemberType NoteProperty -Name "#S" -Value (([regex]::match($Grouping, '#S.*').value) -split " ")[-2]
$collectionVariable.Add($temp) | Out-Null
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.