windows批处理文件按列将csv合并到文件夹中

标签 windows csv batch-file

我想创建一个 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 个具有定义名称的文件组合在一起,或者一个接一个地简单复制。我找不到如何按列复制!

最佳答案

我修改了我在 merge-several-csv-file-side-by-side-using-batch-file 发布的解决方案topic 以便合并通过通配符选择的多个文件(而不是参数中给出的文件)。该解决方案可以处理“可变数量的文件”,但最多只能将 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

关于windows批处理文件按列将csv合并到文件夹中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32238565/

相关文章:

windows - 使用 dpiawareness=1 时辅助监视器的坐标很奇怪

windows - Perl(windows和linux的区别)

javascript - 如何使用按钮切换 d3.js 中的 .csv 文件?

windows - 任务列表未检测/支持超过 21 个字符的进程名称

delphi - 从Windows控制台启动一个GUI程序,然后将其设置为 'detach'

c++ - 使用其他目录中的库构建项目。 Windows , MinGW

我可以让 Unix 的 pthread.h 在 Windows 中编译吗?

python - 如何将默认值插入缺失的 csv 字段?

python - CSV 字符串在 python 列表中转换为十进制

windows - 批量删除小于一定大小的文件