42

Hello I'm looking for powershell script which would merge all csv files in a directory into one text file (.txt) . All csv files have same header which is always stored in a first row of every file. So I need to take header from the first file, but in rest of the files the first row should be skipped. I was able to find batch file which is doing exactly what I need, but I have more than 4000 csv files in a single directory and it takes more than 45 minutes to do the job.

@echo off
ECHO Set working directory
cd /d %~dp0
Deleting existing combined file
del summary.txt
setlocal ENABLEDELAYEDEXPANSION
set cnt=1
for %%i in (*.csv) do (
 if !cnt!==1 (
 for /f "delims=" %%j in ('type "%%i"') do echo %%j >> summary.txt
) else (
 for /f "skip=1 delims=" %%j in ('type "%%i"') do echo %%j >> summary.txt
 )
 set /a cnt+=1
 )

Any suggestion how to create powershell script which would be more efficient than this batch code?

Thank you.

John

16 Answers 16

81

If you're after a one-liner you can pipe each csv to an Import-Csv and then immediately pipe that to Export-Csv. This will retain the initial header row and exclude the remaining files header rows. It will also process each csv one at a time rather than loading all into memory and then dumping them into your merged csv.

Get-ChildItem -Filter *.csv | Select-Object -ExpandProperty FullName | Import-Csv | Export-Csv .\merged\merged.csv -NoTypeInformation -Append
Sign up to request clarification or add additional context in comments.

6 Comments

Is there a way for this to work with PowerShell version 2? It's the only version I have, and it doesn't include the -Append option in Export-Csv
This is definitely the simplest solution - so long as all the source CSV files have the same set of columns in the same order. If the source files have different columns (or orders) and you want a superset file you'll need to pipe the Import-Csv output into a System.Data.DataTable, adding columns as you go, and pipe the final DataTable out to Export-Csv.
This is the "true" PowerShell answer; other answers do not take advantage of key PowerShell functionalities
Is there a way to improve the performance of this? e.g. Multi-threading? Just tried to combine a hundred CSVs totalling 2.6 GB taking >30 mins and CPU/Disk usage never touched ~10% of max capacity, so it's neither cpu nor disk bound which means it's just doing everything in a single thread.
just learned the fun way why you have to put the output in a different location... and a neat way to warm up the room rofl. Otherwise, on your 2nd attempt GCI will grab the output file into the pipeline, and circular-update itself forever lol.
|
58

This will append all the files together reading them one at a time:

get-childItem "YOUR_DIRECTORY\*.txt" 
| foreach {[System.IO.File]::AppendAllText
 ("YOUR_DESTINATION_FILE", [System.IO.File]::ReadAllText($_.FullName))}

# Placed on seperate lines for readability

This one will place a new line at the end of each file entry if you need it:

get-childItem "YOUR_DIRECTORY\*.txt" | foreach
{[System.IO.File]::AppendAllText("YOUR_DESTINATION_FILE", 
[System.IO.File]::ReadAllText($_.FullName) + [System.Environment]::NewLine)}

Skipping the first line:

$getFirstLine = $true

get-childItem "YOUR_DIRECTORY\*.txt" | foreach {
    $filePath = $_

    $lines =  $lines = Get-Content $filePath  
    $linesToWrite = switch($getFirstLine) {
           $true  {$lines}
           $false {$lines | Select -Skip 1}

    }

    $getFirstLine = $false
    Add-Content "YOUR_DESTINATION_FILE" $linesToWrite
    }

2 Comments

This code is almost doing exactly what I need. And it is quite fast but I need to read a header (first row) only from first file. In all other files the first row should be skipped. get-childItem . *.csv | foreach {[System.IO.File]::AppendAllText(".\summary.txt", [System.IO.File]::ReadAllText($_.FullName))}
This is great. Just what I wanted as well.
13

Try this, it worked for me

Get-Content *.csv| Add-Content output.csv

1 Comment

This method does not skip the header row. It will put the header from every file in the merged csv.
7

This is pretty trivial in PowerShell.

$CSVFolder = 'C:\Path\to\your\files';
$OutputFile = 'C:\Path\to\output\file.txt';

$CSV = Get-ChildItem -Path $CSVFolder -Filter *.csv | ForEach-Object { 
    Import-Csv -Path $_
}

$CSV | Export-Csv -Path $OutputFile -NoTypeInformation -Force;

Only drawback to this approach is that it does parse every file. It also loads all files into memory, so if we're talking about 4000 files that are 100 MB each you'll obviously run into problems.

You might get better performance with System.IO.File and System.IO.StreamWriter.

4 Comments

Thank you for your answer. Could you please suggest how to implement System.IO.File and System.IO.StreamWriter into your code, because it takes forever to join 4000 files and skip first row from 3999 files.
Arrays are fixed length. If you want to add to a collection, use something like a List. theposhwolf.com/howtos/PS-Plus-Equals-Dangers
@Zachafer Thanks. I'm well aware of the issue, but this is an ancient answer. I have replaced the code with a better pattern.
If your files are on a network share, change Import-Csv -Path $_ to become Import-Csv -Path $_.FullName or the script will think you're working w/ C: That happened to me.
3

The modern Powershell 7 answer:
(Assuming all csv files are on the same directory and have the same amount of fields.)

@(Get-ChildItem -Filter *.csv).fullname | Import-Csv |Export-Csv ./merged.csv -NoTypeInformation

First part of the pipeline gets all the .csv files and parses the fullname (Path + filename + extension), then import CSV takes each and creates an object and then each object gets merged into a single CSV file with only one header.

Comments

2

Your Batch file is pretty inefficient! Try this one (you'll be surprised :)

@echo off
ECHO Set working directory
cd /d %~dp0
ECHO Deleting existing combined file
del summary.txt
setlocal
for %%i in (*.csv) do set /P "header=" < "%%i" & goto continue
:continue

(
   echo %header%
   for %%i in (*.csv) do (
      for /f "usebackq skip=1 delims=" %%j in ("%%i") do echo %%j
   )
) > summary.txt

How this is an improvement

  1. for /f ... in ('type "%%i"') requires to load and execute cmd.exe in order to execute the type command, capture its output in a temporary file and then read data from it, and this is done with each input file. for /f ... in ("%%i") directly reads data from the file.
  2. The >> redirection opens the file, appends data at end and closes the file, and this is done with each output *line*. The > redirection keeps the file open all the time.

4 Comments

Do you think it would be worth it to explain the difference between yours and the OPs?
@Matt - Aacini's removes the need for a counter variable and logic-checking, giving the script fewer things to do inside the loop, making it faster.
Thank you for your help, but for some reason it doesn't work.Error is: "Deleting is not recognized as internal or external command, operable program or batch file. I guess there should be ECHO command before "Deleting existing combined file". But it doesn't work even after I fixed it. There are just a couple of characters in summary file.
@Matt: The two most important differences are: 1. for /f ... in ('type "%%i"') requires to load and execute cmd.exe in order to execute the type command, capture its output in a temporary file and then read data from it, and this is done with each input file. for /f ... in ("%%i") directly read data from the file. 2. The >> redirection open the file, append data at end and close the file, and this is done with each output *line*. The > redirection keeps the file open all the time.
1

Here is a version also using System.IO.File,

$result = "c:\temp\result.txt"
$csvs = get-childItem "c:\temp\*.csv" 
#read and write CSV header
[System.IO.File]::WriteAllLines($result,[System.IO.File]::ReadAllLines($csvs[0])[0])
#read and append file contents minus header
foreach ($csv in $csvs)  {
    $lines = [System.IO.File]::ReadAllLines($csv)
    [System.IO.File]::AppendAllText($result, ($lines[1..$lines.Length] | Out-String))
}

5 Comments

Thank you for your answer but result.txt file is for some reason not in proper format.When I press F4 everything is put together. Also when I press F3 last line of one file is merged together with first line of a new file.
Just edited the code to insert a "NewLine" after each csv line.
Thank you very much. Now it works fine, but it's more than 2 times slower then Kevin's code. Unless somebody has more than couple hundreds of files in a directory it shouldn't matter. Thank you again.
I see, and I can see why, I was writing each individual line separately. If you have the time, try this code... (edited again)
My gut feeling was that calling .NET directly should be faster than “Get-content”/“Add-Content”, but I guess it is not. After testing both versions with a sample of 500 CSV files, “Get-content”/“Add-Content” wins hands down. This [System.IO.File] version: Elapsed Time: 2.254 seconds Kevin’s (“Get-content”/“Add-Content”) version Elapsed Time: 1.741 seconds
1
Get-ChildItem *.csv|select -First 1|Get-Content|select -First 1|Out-File -FilePath .\input.csv -Force #Get the header from one of the CSV Files, write it to input.csv
Get-ChildItem *.csv|foreach {Get-Content $_|select -Skip 1|Out-File -FilePath .\Input.csv -Append} #Get the content of each file, excluding the first line and append it to input.csv

1 Comment

While this may be the answer, a little context/explanation would be helpful to the person asking the question.
1

stinkyfriend's helpful answer shows an elegant, PowerShell-idiomatic solution based on Import-Csv and Export-Csv.

Unfortunately,

  • it is quite slow because it involves ultimately unnecessary round-trip conversion to and from objects.

  • also, even though it shouldn't matter to a CSV parser, the specific format of the files can get altered in the process, because Export-Csv double-quotes all column values, invariably so in Windows PowerShell, by default in PowerShell (Core) 7+, which now offers opt-in control via -UseQuotes and -QuoteFields).

When performance matters, a plain-text solution is required, which also avoids any inadvertent format alteration (just like the linked answer it assumes that all input CSV files have the same column structure).

The following PSv5+ solution:

  • reads each input file's content into memory in full, as a single multi-line string, using Get-Content -Raw (which is much faster than the default line-by-line reading),
  • skips the header line for all but the first file with -replace '^.+\r?\n', using the regex-based -replace operator,
  • and saves the results to the target file with Set-Content -NoNewLine.

Character-encoding caveat:

  • PowerShell never preserves the input character encoding of files, so you may have to use the -Encoding parameter to override Set-Content's default encoding (the same applies to Export-Csv and any other file-writing cmdlets; in PowerShell (Core) 7+ all cmdlets now consistently default to BOM-less UTF-8; but not only do Windows PowerShell cmdlets not default to UTF-8, they use varying encodings - see the bottom section of this answer).
# Determine the output file and remove a preexisting one, if any.
$outFile = 'summary.csv'
if (Test-Path $outFile) { Remove-Item -ErrorAction Stop $outFile }

# Process all *.csv files in the current folder and merge their contents,
# skipping the header line for all but the first file.
$first = $true
Get-ChildItem -Filter *.csv | 
  Get-Content -Raw | 
    ForEach-Object {
      $content = 
        if ($first) { # first file: output content as-is
          $_; $first = $false
        } else { # subsequent file: skip the header line.
          $_ -replace '^.+\r?\n'
        }
      # Make sure that each file content ends in a newline
      if (-not $content.EndsWith("`n")) { $content += [Environment]::NewLine }
      $content # Output
    } | 
      Set-Content -NoNewLine $outFile # add -Encoding as needed.

Comments

1

If you need to scan folder recursively then you can use the approach below

Get-ChildItem -Recurse -Path .\data\*.csv  | Get-Content | Add-Content output.csv

what this basically does is:

  • Get-ChildItem -Recurse -Path .\data\*.csv Find the requested files recursively
  • Get-Content Get content for each
  • Add-Content output.csv append it to output.csv

1 Comment

as pointed out by Mike Deluca, this will include multiple headers and/or type information if those are at the top of the sheets.
1

This scripts should help you achieve your goal

$sourceDir = "C:\path\to\source"
$targetFile = "C:\path\to\target\combined.txt"

# Remove the target file if it exists
if (Test-Path $targetFile) {
    Remove-Item $targetFile
}

# Get all CSV files
$files = Get-ChildItem -Path $sourceDir -Filter *.csv

$firstFile = $true
foreach ($file in $files) {
    if ($firstFile) {
        # Copy the entire first file including the header
        Copy-Item -Path $file.FullName -Destination $targetFile
        $firstFile = $false
    } else {
        # Append subsequent files without the header
        Get-Content $file.FullName | Select-Object -Skip 1 | Add-Content $targetFile
    }
}

1 Comment

Use this method if you know that some files will have headers only and no data rows. Import-Csv will not include headers if trying to read a file with no data, as it cannot read into the data to see what types it should infer for these columns. So, if you use the Import-Csv/Export-Csv method, you may end up with a file with no headers, depending on the content of your files.
0

I found the previous solutions quite inefficient for large csv-files in terms of performance, so here is a performant alternative.

Here is an alternative which simply appends the files:

cmd /c copy  ((gci "YOUR_DIRECTORY\*.csv" -Name) -join '+') "YOUR_OUTPUT_FILE.csv" 

Thereafter, you probably want to get rid of the multiple csv-headers.

Comments

0

The following batch script is very fast. It should work well as long as none of your CSV files contain tab characters, and all source CSV files have fewer than 64k lines.

@echo off
set "skip="
>summary.txt (
  for %%F in (*.csv) do if defined skip (
    more +1 "%%F"
  ) else (
    more "%%F"
    set skip=1
  )
)

The reason for the restrictions is that MORE converts tabs into a series of spaces, and redirected MORE hangs at 64k lines.

1 Comment

Changed TYPE to MORE in case 1st file does not end with new line
0
#Input path
$InputFolder = "W:\My Documents\... input folder"
$FileType    = "*.csv"

#Output path
$OutputFile  = "W:\My Documents\... some folder\merged.csv"

#Read list of files
$AllFilesFullName = @(Get-ChildItem -LiteralPath $InputFolder -Filter $FileType | Select-Object -ExpandProperty FullName)

#Loop and write 
Write-Host "Merging" $AllFilesFullName.Count $FileType "files."
foreach ($FileFullName in $AllFilesFullName) {
    Import-Csv $FileFullName | Export-Csv $OutputFile -NoTypeInformation -Append
    Write-Host "." -NoNewline
}

Write-Host
Write-Host "Merge Complete"

Comments

-1
$pathin = 'c:\Folder\With\CSVs'
$pathout = 'c:\exported.txt'
$list = Get-ChildItem -Path $pathin | select FullName
foreach($file in $list){
    Import-Csv -Path $file.FullName | Export-Csv -Path $pathout -Append -NoTypeInformation
}

Comments

-5

type *.csv >> folder\combined.csv

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.