【问题标题】:windows batch file combine csv in a folder by columnwindows批处理文件按列组合文件夹中的csv
【发布时间】:2015-08-26 23:56:59
【问题描述】:

我想创建一个 Windows 批处理文件,以将一个充满 CSV 的文件夹合并到一个 CSV 文件中,但按列而不是最后。

file1.csv
A, B
1, 2
3, 4
5, 6

...

fileN.csv
C, D
1, 2
3, 4
5, 6

results.csv
A, B, C, D
1, 2, 1, 2
3, 4, 3, 4
5, 6, 5, 6

我见过的所有示例都将 2 个具有定义名称的文件或一个接一个的简单副本组合在一起。我找不到如何按列复制!

【问题讨论】:

  • 必须合并多少个文件?
  • 它们的长度都一样吗?
  • @aacini 可变文件数
  • @jme:超过 9 个文件?超过 81 个文件? PS - 在批处理文件中编程时,所有细节都很重要,可以产生巨大的影响!
  • @jme 如果您的文件有不同的行数,那么这些列将会混乱。任何一行的总长度也是有限的,因此这些细节很重要。

标签: windows csv batch-file


【解决方案1】:

我修改了我在merge-several-csv-file-side-by-side-using-batch-file 主题上发布的解决方案,以便合并通过通配符选择的多个文件(而不是参数中给出的文件)。此解决方案可以处理“可变数量的文件”,但最多只能将 8 个文件合并到另一个文件中;如果文件超过 8 个,则会在“mergedFiles”文件夹中创建多个“合并文件”,每个文件最多 8 个文件。如果您想从超过 8 个文件中生成一个文件,则必须对“mergedFiles”文件夹中的文件重复该过程。

@echo off
setlocal EnableDelayedExpansion

rem MergeFiles2.bat: Merge several files horizontally, version 2
rem Antonio Perez Ayala

rem Get the list of files to merge into "file" array
set "num=0"
for %%a in (*.csv) do (
   set /A num+=1
   set "file[!num!]=%%a"
)

rem Merge files from the "file" array
set /A merge=0, last=0
if not exist mergedFiles\ md mergedFiles

:nextMerge
set /A merge+=1, first=last+1, last+=8
if %last% gtr %num% set last=%num%

rem Assemble the lists of redirections and SET /P commands for this merge
set "file1=!file[%first%]!"
echo/
echo The following files:
echo - %file1%
set /A first+=1
set "redirs="
set "commands="
set handle=2
for /L %%i in (%first%,1,%last%) do (
   echo - !file[%%i]!
   set /A handle+=1
   set "redirs=!redirs! !handle!<"!file[%%i]!" "
   set "commands=!commands! & set /P "line=^^!line^^!, " ^<^&!handle!"
)
if defined commands set "commands=!commands:~3!"
echo will be merged into:  mergedFiles\file%merge%.csv

rem First file in this merge is read with FOR /F command
rem The rest of files are read via standard handles, starting at # 3

%redirs% (
   for /F "usebackq delims=" %%a in ("%file1%") do (
      rem Get a line from first file
      set "line=%%a"
      rem Write-Read lines from all files, excepting the last one
      %commands%
      rem Write the line from last file
      echo !line!
   )
) > mergedFiles\file%merge%.csv

if %last% lss %num% goto nextMerge

【讨论】:

    猜你喜欢
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 2022-10-05
    相关资源
    最近更新 更多