batch-file - 合并不带标题的 CSV 文件

标签 batch-file csv merge cmd

我进行了广泛的搜索,并找到了我认为可以解决我的问题的方法,即合并 CSV 文件,而无需每次都重复标题。看起来它可以工作,只是它只是将文件夹中的第一个文件复制到目标文件中。我认为它无法打开文件,因为它们的名称中有空格。有人建议我可能只需要在某个地方加上引号,但我不确定它们会放在哪里。提前致谢。

@ECHO OFF
SET first=y
SET newfile=new.csv
for %%F in (*.csv) do IF NOT %%F==%newfile% (
  if defined first (
    COPY /y "%%F" %newfile% >nul
    set "first="
  ) else (
    FOR /f "skip=1delims=" %%i IN (%%F) DO >> %newfile% ECHO %%i
  )
)

最佳答案

@echo off
    setlocal enableextensions disabledelayedexpansion

    rem configure paths
    set "source=*.csv"
    set "target=newfile.csv"

    rem remove output file if needed
    if exist "%target%" del "%target%" >nul 2>nul

    rem search for header row
    set "headerRow="
    for %%f in ("%source%") do (
        <"%%~ff" ( for /l %%a in (1 1 10) do if not defined headerRow set /p "headerRow=" )
        if defined headerRow goto haveHeader
    )
:haveHeader
    if not defined headerRow (
        echo ERROR: impossible to get header row. 
        goto endProcess
    )

    rem output header to header file to use as filter.
    rem header is cut to avoid findstr limitations on search strings
    set "headerFile=%temp%\%~nx0_headerFile.tmp"
    setlocal enableextensions enabledelayedexpansion
    > "%headerFile%" echo(!headerRow:~0,125!
    endlocal


    rem search for input files with matching headers to join to final file
    for /f "tokens=*" %%f in ('findstr /m /b /l /g:"%headerFile%" "%source%"') do (
        if not exist "%target%" (

                rem first file is directly copied
                copy "%%~f" "%target%" /y > nul 2>nul

            ) else (

                rem next files are filtered to exclude the header row
                findstr /v /b /l /g:"%headerFile%" "%%~f" >> "%target%"
        )
        echo ... [%%~ff] joined to %target%
    )

    rem remove the temporary header file
    del "%headerFile%" >nul 2>nul

:endProcess
    endlocal

关于batch-file - 合并不带标题的 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21318868/

相关文章:

windows - 在新的 CMD 实例中自动启动程序

windows - 在 cmd.exe 中执行批处理文件什么都不做

powershell - 将带引号的参数从批处理文件传递给 `powershell start` - 按需 self 提升

linux 创建一个文件,其中包含 csv 中的文件标题

python - 多索引合并返回空 df 但连接应该有效

batch-file - 如何使用命令提示符使用名称列表重命名文件?

python-3.x - 解决Pandas数据框中带引号分号的csv文件

python - 搜索列,使用 python 从 excel 返回行

eclipse - 以编程方式使用 Eclipse 的合并和差异查看器

r - 一种更优雅的方式,将两个向量组合为单独的列(或数据帧),匹配行,并在不匹配的地方具有 NA