Merging multiple CSV files into one using PowerShell

后端 未结 11 1608
慢半拍i
慢半拍i 2020-11-27 17:47

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

11条回答
  •  感情败类
    2020-11-27 18:15

    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.

提交回复
热议问题