Merge multiple CSVs with PowerShell
Use this simple PowerShell script to merge multiple CSV/TSV/TXT files into one.
I’ve previously described how to convert a CSV into an XLSX and even multiple CSVs into one XLSX file. But what if all I want to do is stitch a few CSV files into one?
The following script will do just that: combine all of the CSV files in a directory into a single CSV file. This code will take the header from the first file for use in the new stitched CSV. Headers in the remaining source files will be ignored.
$getFirstLine = $true
get-childItem "c:\path\to\files\*.csv" | foreach {
$filePath = $_
$lines = Get-Content $filePath
$linesToWrite = switch($getFirstLine) {
$true {$lines}
$false {$lines | Select -Skip 1}
}
$getFirstLine = $false
Add-Content "c:\path\to\files\final.csv" $linesToWrite
}
This will also work for TSV and TXT files. Simply change the file extensions in the above script.
Comments
11 responses to “Merge multiple CSVs with PowerShell”
Thank you,
How to merge them in a unique CSV putting every single CSV in a different tab?
(nice blog by the way!)
Nice little script! Looks like there might be a minor (non-error) typo:
(The script still works, but it might be confusing to some people wondering why it assigns to the $lines variable twice).
Anyway thanks for this. Always love reusing someone else’s code for common tasks rather than writing it myself.
Thanks, so much faster than using cmd
I suppose this is a typo:
Thanks Anthony and Andrea for the corrections. The script is updated.
Very helpful script, thanks. I wanted all contents to be merged, changing the skip to 0 from 1 did the trick
Brilliant solution!
This is way faster than using cmd line code.
How can I get in this merge as well the file name into a separated column?
it should be like:
Name Town Filename
Roger Zurich File1
Thomas Basel File2
Awesome Script!!
get-content *.csv | add-content final.csv
Only returns the first CSV encountered.