合并2个csv文件

时间:2013-11-20 15:11:55

标签: batch-file csv merge

我想合并2个csv文件。例如,csv1文件包含前六列,csv2文件包含(前6列为空)第7,第8,第9列。在合并的csv中,我需要它(前6列 - 第一个csv和7,8,9- ---第二次csv)。请帮助我

提前致谢

4 个答案:

答案 0 :(得分:2)

我们假设file1.csv包含这种格式的行:

col1,col2,col3,col4,col5,col6

并且file2.csv包含具有以下格式的行:

,,,,,,col7,col8,col9

下面的批处理文件用file1中的col1..col6和file2中的col7..col9创建合并文件;它假设两个文件的行数相同,并且任何文件中都没有空行。

@echo off
setlocal EnableDelayedExpansion

< file2.csv (
   for /F "delims=" %%a in (file1.csv) do (
      set /P line2=
      echo %%a,!line2:~6!
   )
) > merged.csv

答案 1 :(得分:0)

这对于批处理命令来说要困难得多。如果你考虑使用VBS或perl然后在批处理文件中调用脚本,那么它会更容易。

答案 2 :(得分:0)

我认为文件不是太大而无法将它们加载到内存中,并且每个csv文件中的行数不超过999999行。当脚本结束时,CMD将立即退出。

@echo off
setlocal enabledelayedexpansion
set file1Content=
set file2Content=

rem Read first file in "file1Content" variable, split lines by slash
for /f %%a in (Document1.csv) do (
    set file1Content=!file1Content!/%%a
)
rem Remove first leading slash
set file1Content=!file1Content:~1!

rem Read second file in "file2Content" variable, split lines by slash
for /f %%a in (Document2.csv) do (
    set file2Content=!file2Content!/%%a
)
rem Remove first leading slash
set file2Content=!file2Content:~1!

set rest1=
set rest2=
for /L %%a in (1,1,999999) do (
    set item1=
    set item2=
    rem Take first line from "!file1Content!"
    for /f "tokens=1,* delims=/" %%x in ("!file1Content!") do (
        set item1=%%x
        set rest1=%%y
    )
    rem Removing first line (the one we read) from content1
    set file1Content=!rest1!
    rem Exit if there's no content
    if "!item1!"=="" exit

    rem Take first line from "!file2Content!"
    for /f "tokens=1,* delims=/" %%x in ("!file2Content!") do (
        set item2=%%x
        set rest2=%%y
    )
    rem Removing first line (the one we read) from content2
    set file2Content=!rest2!
    rem Exit if there's no content
    if "!item2!"=="" exit
    echo !item1!,!item2!>>joined.csv    
)

答案 3 :(得分:0)

    Here is the command for doing it the easy way

    cut -c7- y.txt | paste -d',' x.txt - > z.txt

    The 'cut' command cuts off the first 6 characters of file y.txt
    The 'paste' command puts together file x.txt with that modified y.txt
    using comma for a separator and puts the results in file z.txt

    for example:

    file x.txt
    col1,col2,col3,col4,col5,col6
    col1,col2,col3,col4,col5,col6
    col1,col2,col3,col4,col5,col6
    col1,col2,col3,col4,col5,col6

    file y.txt
    ,,,,,,col7,col8,col9
    ,,,,,,col7,col8,col9
    ,,,,,,col7,col8,col9
    ,,,,,,col7,col8,col9

    cut -c7- y.txt | paste -d',' x.txt - > z.txt

    file z.txt
    col1,col2,col3,col4,col5,col6,col7,col8,col9
    col1,col2,col3,col4,col5,col6,col7,col8,col9
    col1,col2,col3,col4,col5,col6,col7,col8,col9
    col1,col2,col3,col4,col5,col6,col7,col8,col9