【问题标题】:how to convert text to csv file which having delimiter '|' in powershell如何将文本转换为具有分隔符'|'的csv文件在PowerShell中
【发布时间】:2022-01-11 14:01:45
【问题描述】:

代码:

$file= Get-Content "C:\Users\phm4\Desktop\source\status.txt" | select -first 18

$new=$file | select -Skip 12
$nospace=($new)-replace '\s' 
$nospace | Out-File new1.txt

import-csv new1.txt -Delimiter "|" | export-csv csvfile.csv

样本数据:

1|10.9.7.73|-A--|0|505k|505k|2.4T/52.7T(5%)|L3:1.5T
2|10.9.7.74|OK|0|608k|608k|2.4T/52.7T(5%)|L3:1.5T
3|10.9.7.75|OK|0|626k|626k|2.4T/52.7T(5%)|L3:1.5T
4|10.9.7.76|OK|0|0|0|2.4T/52.7T(5%)|L3:1.5T
5|10.9.7.77|OK|0|0|0|2.4T/52.7T(5%)|L3:1.5T
6|10.9.7.78|OK|0|398k|398k|2.4T/52.7T(5%)|L3:1.5T

【问题讨论】:

  • 为什么不从一开始就使用$file= Import-Csv -Path "C:\Users\phm4\Desktop\source\status.txt" -Delimiter '|'
  • 问题是什么?当前方法的表现如何?

标签: windows powershell csv export-to-csv


【解决方案1】:

您不能直接在文本文件上使用 Import-Csv 的原因是因为正确的 CSV 文件具有必须是唯一的标题,而您显示的示例没有标题。
这意味着 PowerShell 将使用顶行作为标题,但不能,因为那时有两列名为 '505k'..

你可以做的是:

# get the lines you're interested in and repace whitespaces
$data = Get-Content -Path 'D:\Test\test.txt' -TotalCount 18 | Select-Object -Skip 12 | ForEach-Object { $_ -replace '\s' }

# first find out how many headers you need and create them (as demo, they will be called 'Column_1' etc.)
$n = (($data | ForEach-Object { ($_ -split '\|').Count }) | Measure-Object -Maximum).Maximum
$headers = 1..$n | ForEach-Object { "Column_$_" }

对我来说,是否希望生成的带有管道符号 | 作为分隔符的 csv 文件不是很清楚,但如果是这种情况,只需将数据写回包含这些标题的文件即可:

# join the created $headers array with the pipe symbol and write to file
($headers -join '|') | Set-Content -Path 'D:\Test\csvfile.csv'
$data | Add-Content -Path 'D:\Test\csvfile.csv'

但是,如果您不想要管道,而是使用不同的字符作为分隔符,请使用:

# for demo output a csv with the default comma as delimiter
$data | ConvertFrom-Csv -Header $headers -Delimiter '|' | Export-Csv -Path 'D:\Test\csvfile2.csv' -NoTypeInformation

【讨论】:

    【解决方案2】:

    导入文本文件使用 import-csv 然后导出它使用 export-csv

    
    $path = "C:\Users\phm4\Desktop\source\status.txt"
    $csv = "C:\Users\phm4\Desktop\source\csvfile.csv"
    $import = import-csv $path -Delimiter "|" 
    $import | export-csv $csv
    

    【讨论】:

    • import-csv :成员“505k”已经存在。在 line:3 char:11 + $import = import-csv $path -Delimiter "|" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Import-Csv], ExtendedTypeSystemException + FullyQualifiedErrorId :已经存在PSMemberInfoInternalCollectionAdd,Microsoft.PowerShell.Commands.ImportCsvCommand
    • 出现这样的错误
    • csv 文件有一个重复的列名,假定为“501k”。 PowerShell 不支持。试试 $import = Import-Csv $path -Header A,B,C,D,E,F,G -Delimiter "|"
    猜你喜欢
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多