2

I have a batch script that runs two sensor collectors in to two separate csv files.

I'd like to run a command at the end of the script that merges the two files line by line.

ie: File1:

1,2,3
1,2,3
1,2,3

File2

x,y,z
x,y,z
z,y,z

Merged File:

1,2,3,x,y,z
1,2,3,x,y,z
1,2,3,x,y,z
1

2 Answers 2

2
powershell $f1=gc File1;$f2=gc File2;for($i=0;$i-lt$f1.length;++$i){$f1[$i]+','+$f2[$i]}>Merged-File.txt

Update 1:

powershell $f1=gc File1;$f2=gc File2;$i=0;$f1^|%{$f1[$i]+','+$f2[$i];++$i}>Merged-File.txt
1
  • @RevTyler Update. Thx)
    – STTR
    Oct 2, 2014 at 10:26
0

For a batch solution, you can try

@echo off
    setlocal enableextensions disabledelayedexpansion

    rem configure files to merge
    set "file1=file1.csv"
    set "file2=file2.csv"

    rem find how many lines we need to merge
    for /f %%a in ('find /c /v "" ^< "%file1%"') do set "lines=%%a"
    if "%lines%" lss "0" goto :eof

    rem define input streams for both files    
    8<"%file1%" 9<"%file2%" (

        rem For each of the lines, read from file1 and file2, with 
        rem delayed expansion disabled to avoid problems with possible !
        rem Then delayed expansion is enabled, lines printed, and 
        rem delayed expansion disabled again

        for /l %%a in (1 1 %lines%) do (
            set /p "line1=" <&8 || exit /b
            set /p "line2=" <&9 || exit /b
            setlocal enabledelayedexpansion
            echo(!line1!,!line2!
            endlocal
        )

    ) > "outputFile.csv"
    rem Send all the output to the final file

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .