我有一个CSV文件,需要将分隔符从逗号更改为分号。我用下面的命令修复了这个问题
(Import-CSV $File) | Export-Csv $File -delimiter ';' -notypeinformation但是当导入的CSV文件只包含一行时,我假设这行是作为头处理的。它删除了输出文件中的这一行,它就变成了一个空文件。但是,当我有多行代码,并且csv包含头文件和一些数据时,导出的文件可以正确地使用头文件和数据执行。
我用来在脚本开头设置头文件的代码
#set csv headers
Set-Content -Path "$FolderNameCiTypeDelta" -Value "name,type,location,size"我试着添加代码
(Import-CSV $File -Header "name,type,location,size") | Export-Csv $File -delimiter ';' -notypeinformation 但是这只增加了我指定的头的一行。
编辑
我用来测试的两个csv文件包含以下行
使用import --> export命令变为空的文件包含
name,type,location,size使用import --> export命令执行所需操作的文件包含
name,type,location,size
test,extra,line发布于 2020-01-17 23:32:41
您可以执行以下操作:
$file = 't.txt'
$contents = Get-Content $file -totalcount 2
if ($contents.Count -gt 1) {
(Import-Csv $file) | Export-Csv $file -Delimiter ';' -NoType
}
if ($contents.Count -eq 1) {
$contents -replace ',',';' | Set-Content $file
}这里的想法是读取文件中的两行。如果它只包含一行,它将使用-replace来修复分隔符。如果它有两行以上,它将使用*-Csv命令。
只有当您的字段值中没有逗号时,-replace部分才有效。如果字段中有逗号,那么字段两边应该有文本限定符(最有可能是双引号)。在这种情况下,您可以简单地使用-replace '","','";"'。
https://stackoverflow.com/questions/59789038
复制相似问题