我是powershell新手,我有一个像这样的.csv文件:
Group1; User_A
Group1; User_B
Group2; User_A
Group2; User_D
Group2; User_C
如何从第一列替换带有空格的项目,以便我只获得组中的第一项:
Group1; User_A
; User_B
Group2; User_A
; User_D
; User_C
我试过像
这样的东西$header = "Group", "User"
$adg = Import-Csv "C:\temp\users.csv" -Header $header -Delimiter ";"
$adg | ForEach-Object {$_ -replace "Group1", ""}
但我不知道如何继续
答案 0 :(得分:2)
这样的事情怎么样:
$csv = Import-Csv "Test.csv" -Header "Group", "User" -Delimiter ";"
$lastGroup = ""
$csv | % {
if ($lastGroup -eq $_.Group) {
$_.Group = ""
} else {
$lastGroup = $_.Group
}
}
$csv | ConvertTo-Csv -Delimiter ';' -NoTypeInformation
输出:
"Group";"User"
"Group1";"User_A"
"";"User_B"
"Group2";"User_A"
"";"User_D"
"";"User_C"
<强>更新强>
只是为了好玩,这里的版本输出的内容与您的示例完全相同:
$csv = Import-Csv "C:\Documents and Settings\arisman1\Desktop\Test.csv" -Header "Group", "User" -Delimiter ";"
$lastGroup = ""
$longestGroupName = $csv | select -Expand Group | Measure-Object -Property Length -Maximum
$csv | % {
if ($lastGroup -eq $_.Group) {
$_.Group = " " * $longestGroupName.Maximum
} else {
$lastGroup = $_.Group
}
}
$csv | ConvertTo-Csv -Delimiter ';' -NoTypeInformation | % {$_ -replace '"', ''} | select -Skip 1
输出:
Group1;User_A
;User_B
Group2;User_A
;User_D
;User_C