powershell - 如何确定文件在 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
}
}
解决方案
另一种方法是用于Select-String
检查制表符并设置分隔符。
if(Get-Content $csvfile -First 1 | Select-String -Pattern "`t")
{
$delim = "`t"
}
else
{
$delim = ','
}
Import-Csv $csvfile -Delimiter $delim
推荐阅读
- python - 使用 OpenCV Python,显微视频
- c++ - 如何在 C++ 中递归地将十六进制转换为十进制?
- safari - Branchio Universal Deeplink 重定向到 safari 并显示弹出窗口以启动应用程序,即使应用程序安装在 iOS 13.3.1 中
- python - 如何在主应用程序 Pyqt 中插入产生其他线程的 matplotlib 图 ..?
- macos - Mac 上的 Google Chrome 中的区域设置代码不正确
- artifactory - Artifactory Pro 从 6.x 升级到 7.x 后出现 404
- docker - 在 k8s 进程中,“kube-controller-manager”是来自 docker conainer 的“子进程”。为什么 k8s 有这样的架构?
- python - 将标头写入文件时键入错误:python3
- kubernetes - kubectl exec 失败并显示错误“无法使用 TTY - 输入不是终端或正确的文件类型”
- parsing - 将数据从 kafka 摄取到 elasticsearch 时 kibana 中的字符编码问题