Skip to content

Dear Internet Explorer user: Your browser is no longer supported

Please switch to a modern browser such as Microsoft Edge, Mozilla Firefox or Google Chrome to view this website's content.

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

8 responses to “Merge multiple CSVs with PowerShell”

On 6 November 2018, Frrancesco wrote: Hyperlink chain icon

Thank you,
How to merge them in a unique CSV putting every single CSV in a different tab?

(nice blog by the way!)

Reply

On 21 December 2018, Anthony J. wrote: Hyperlink chain icon

Nice little script! Looks like there might be a minor (non-error) typo:

$lines =  $lines = Get-Content $filePath

(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.

Reply

On 9 January 2019, David wrote: Hyperlink chain icon

Thanks, so much faster than using cmd

Reply

On 23 January 2019, Andrea Coccanari wrote: Hyperlink chain icon

I suppose this is a typo:

$lines =  $lines = Get-Content $filePath

Reply

On 29 January 2019, Adam Dimech wrote: Hyperlink chain icon

Thanks Anthony and Andrea for the corrections. The script is updated.

Reply

On 3 April 2020, George Suprith wrote: Hyperlink chain icon

Very helpful script, thanks. I wanted all contents to be merged, changing the skip to 0 from 1 did the trick

Reply

On 14 July 2020, Hamid Ashari wrote: Hyperlink chain icon

Brilliant solution!
This is way faster than using cmd line code.

Reply

On 22 August 2020, Roger Erne wrote: Hyperlink chain icon

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

Reply

Have Your Say

The following HTML is permitted:
<a href="" title=""> <b> <blockquote cite=""> <code> <em> <i> <q cite=""> <strike> <strong>

Comments will be published subject to the Editorial Policy.