我使用Import-CSV
从csv文件中获取数据,如下所示:
P1,1,3,4
P2,4,5,6
P3,1,2,3
P4,8.7,6,3
我想将白色空间保留在文本前面,因为它表示层次结构。 Import-CSV
返回:
P1,1,3,4
P2,4,5,6
P3,1,2,3
P4,8.7,6,3
有没有办法保留空白区域?
答案 0 :(得分:2)
您的CSV格式不正确,每行中的项目都应引用以符合文件规范:
"P1,"1","3","4" " P2,"4","5","6" " P3,"1","2","3" " P4,"8.7","6","3"
您可以使用快捷方式,只包含带引号的前导空格的条目:
P1,1,3,4 " P2",4,5,6 " P3",1,2,3 " P4",8.7,6,3
然后Import-CSV
将按照您的预期运行,为演示添加标题:
Import-CSV leading_spaces.csv -Header "Field1","Field2","Field3","Field4"
为您提供所需的输出:
Field1 Field2 Field3 Field4 ------ ------ ------ ------ P1 1 3 4 P2 4 5 6 P3 1 2 3 P4 8.7 6 3
答案 1 :(得分:0)
根据James C's comment,您可以使用Get-Content
:
$myData = Get-Content .\test2.txt
foreach($line in ($myData | Select-Object -Skip 1)){
[array]$results += [pscustomobject]@{
$myData[0].Split(",")[0] = $line.Split(",")[0]
$myData[0].Split(",")[1] = $line.Split(",")[1]
$myData[0].Split(",")[2] = $line.Split(",")[2]
$myData[0].Split(",")[3] = $line.Split(",")[3]
}
}
答案 2 :(得分:0)
也许这会有所帮助,它会为每一行创建一个新对象:
get-content test.csv | % {
$row = New-Object PSObject
$i = 0
$_ -split "," | %{
$row | add-member Noteproperty "column$i" $_
$i++
}
$row
}
输出将如下所示:
column0 column1 column2 column3
------- ------- ------- -------
P1 1 3 4
P2 4 5 6
P3 1 2 3
P4 8.7 6 3