如何使用PowerShell将多个文本文件的列合并到一个csv文件中?

问题描述:

我有多个测量文件,每个文件都有一列数字数据. (更新:该脚本应适用于可变数量的测量文件.)

I have got multiple measurement files with one column of numeric data each. (Update: The script should work for variable numbers of measurement files.)

data1.dat

1.0
2.0
3.0

data2.dat

10.0
20.0
30.0

...

dataN.dat

1
1
1

如何使用 Powershell 将这些数据文件合并为逗号分隔的值文件?

How can I merge these data files into a comma separated values file using Powershell?

"data1","data2.dat",...,"dataN.dat"
1.0,10.0,...,1
2.0,20.0,...,1
3.0,30.0,...,1

相关

  • Merging Two Text Files into One CSV File does not help my case, but might help other people who search for column merging.
  • Powershell / Perl : Merging multiple CSV files into one? is similar but there the lines have an id.

这是一种方法:

$files = Get-ChildItem D:\temp *.dat
$header = $files|foreach {$_.basename}
$content= $files | foreach { ,(gc $_.fullname) }

$lines = for($i=0; $i -lt $content[0].Count; $i++)
{
    $line = for($x=0; $x -lt $files.count; $x++)
    {
        $content[$x][$i]        
    }

    $line -join ','
}

$lines | ConvertFrom-Csv -Header $header | Export-Csv data.csv