首页 > 解决方案 > 如何确定文件在 PowerShell 中是制表符分隔的?

问题描述

我有一个正在处理的脚本,它读取一些文本文件并将它们转换为 .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 
}
}

标签: powershellcsv

解决方案


另一种方法是用于Select-String检查制表符并设置分隔符。

if(Get-Content $csvfile -First 1 | Select-String -Pattern "`t")
{
    $delim = "`t"
}
else
{
    $delim = ','
}

Import-Csv $csvfile -Delimiter $delim

推荐阅读