How to merge colums of multiple text files into one csv file using PowerShell?

前端 未结 2 675
小鲜肉
小鲜肉 2021-01-26 11:21

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

相关标签:
2条回答
  • 2021-01-26 11:49

    You could try something like this:

    $file1 = "C:\firstTxtFile.txt"
    $file2 = "C:\SecondTxtFile.txt"
    $outputFile = "C:\Output.txt"
    
    $file1String = Get-content $file1 
    $file2String = Get-content $file2
    
    '"data1.dat","data2.dat"' > $outputFile
    
    $counter = 0
    while(($file1String[$counter] -ne $null) -and ($file2String[$counter] -ne $null)){
        $Line = $file1String[$counter] + "," + $file2String[$counter]
        $line >> $outputFile
        $counter++
    }
    

    This will take two text file and combine them into one output file.

    Note: The output file will be overwritten each time this is run.

    0 讨论(0)
  • 2021-01-26 11:51

    Here's one way:

    $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
    
    0 讨论(0)
提交回复
热议问题