使用 Powershell 获取第三列并将其放入所有 CSV 文件的另一个文件中

问题描述 投票:0回答:1

我有一个文件夹,其子文件夹中充满了 csv 文件。 对于每个文件,我只想获取第三列并将其保存在另一个文件中。

示例:

文件数据1.csv

aa,bb,cc
cat,horse,"dog, bird"
4th,33,first and second

文件数据1列3.csv

cc
dog, bird
first and second

我尝试过但结果是错误的:

param ( [String] $Filename  = '*.csv',
            [String] $SourceDir = 'C:\Data\',
    )
    
ForEach ($csvFile in Get-ChildItem -Path $SourceDir -Filter $Filename){
            (Import-Csv $csvFile)
            cut -d, -f 3 *.csv > *column3.csv
powershell csv cut
1个回答
1
投票
# Import all rows.
$rows = Import-Csv $csvFile
# Determine the name of the third column
$thirdColName = ($rows[0].psobject.Properties.Name)[2]

# Determine a suitable output file path and name.
$outFile =
  Join-Path $csvFile.DirectoryName ('{0}_column3.csv' -f $csvFile.BaseName)

# Output the header column
$thirdColName > $outFile
# Append the values of the third column
$rows.$thirdColName >> $outFile

注:

  • Windows PowerShell 中,

    >
    >>
    创建“Unicode”(UTF-16LE) 文件,而在 PowerShell (Core) 7+ 中,它们创建无 BOM 的 UTF-8 文件。

  • 如果您需要不同的编码,请使用

    Set-Content
    Add-Content
    以及
    -Encoding
    参数,但请注意,在 Windows PowerShell 中,您无法以这种方式创建 BOM-less UTF-8 文件(请参阅此答案用于解决方法)。

© www.soinside.com 2019 - 2024. All rights reserved.