【发布时间】:2020-09-15 16:22:21
【问题描述】:
我正在编写一个脚本,它读取一些文本文件并将它们转换为 .csv 并更改一些值。我有两个不同的文件源。一个是制表符分隔的 .txt 文件,另一个是逗号分隔的 .txt 文件。有没有办法确定使用哪种类型的分隔符来确定哪种导出函数合适?
get-childitem $workingDir -filter *.txt -Recurse| ForEach-Object {
$targetfile = $_.Name
$targetFile = $_.FullName.Substring(0,$_.FullName.Length-4)
$targetFile = $targetfile += ".csv"
if( Get-Content -Delimiter = `t ){
Write-Host "The file is tab-delimited"
Get-Content -path $_.FullName
ForEach-Object {$_ -replace “`t”,”,” } |
Out-File -filepath $targetFile -Encoding utf8
}
else {
Write-Host "The file is comma-separated"
Get-Content -path $_.FullName |
Out-File -filepath $targetFile -Encoding utf8
}
}
【问题讨论】:
-
阅读第一行并测试它的标签比逗号多:)
-
可以读取第一行并检查它是否是使用这两种方法的有效对象?可以说逗号分隔的文件不包含任何制表符,反之亦然吗?
-
@mhouston100,您可以从接受的答案中推断逗号分隔的文件确实假定不包含制表符。另一个答案显示如何仅检查第一行。
标签: powershell csv