Skip to content

Merge multiple CSVs with PowerShell

G28th June 2016

C6 Comments

TExcel, 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:

6 responses to “Merge multiple CSVs with PowerShell”

  • Written by Frrancesco on 6 November 2018:

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

    (nice blog by the way!)

  • Written by Anthony J. on 21 December 2018:

    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.

  • Written by David on 9 January 2019:

    Thanks, so much faster than using cmd

  • Written by Andrea Coccanari on 23 January 2019:

    I suppose this is a typo:

    $lines =  $lines = Get-Content $filePath
  • Written by Adam Dimech on 29 January 2019:

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

  • Written by George Suprith on 3 April 2020:

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

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.