我需要将数据添加到CSV文件的最后一列。我拥有的测试文件如下:
NAME,AGE,OFFICE,DEPT,SKILL jack,24,IBM,Retail tom,32,MS,BFSI SAM,44,MGR,Test
我设法解析了CSV,但是很难将数据添加到最后一列“ SKILL”。要求是将单词“ Java”添加到每一行的最后一列
NAME,AGE,OFFICE,DEPT,SKILL jack,24,IBM,Retail,Java tom,32,MS,BFSI,Java SAM,44,MGR,Test,Java
请注意,添加到最后一列的值在各行中保持不变。
答案 0 :(得分:3)
您可以更改导入对象的SKILL
属性值,并通过以下方法导出到CSV文件:
Import-Csv test.txt |
ForEach-Object {$_.SKILL = "Java"; $_} |
Export-Csv test_out.txt -NoTypeInformation
但是Export-Csv
会在值周围加上引号,因此test_out.txt
看起来像这样:
"NAME","AGE","OFFICE","DEPT","SKILL"
"jack","24","IBM","Retail","Java"
"tom","32","MS","BFSI","Java"
"SAM","44","MGR","Test","Java"
也许您应该简单地在每行第二行的末尾添加",Java
“:
Get-Content test.txt |
ForEach-Object { if($_.ReadCount -gt 1) { "$($_),Java" } else { $_ } } |
Out-File test_out.txt
答案 1 :(得分:0)
您可以简单地创建一个包含当前csv数据的对象,并使用字符串Java
扩展该对象,如下所示:
$results = @() # Empty array to store new created rows in
$csv = Import-Csv "$PSScriptRoot\csvfile.csv"
foreach ($row in $csv) {
$properties = [ordered]@{
NAME = $row.NAME
AGE = $row.AGE
OFFICE = $row.OFFICE
DEPT = $row.DEPT
SKILL = "Java"
}
# insert the new row as an object into the results-array
$results += New-Object psobject -Property $properties
}
# foreach-loop filled the results-array - export it as a CSV-file
$results | Export-Csv "new-file.csv" -NoTypeInformation