使用 Windows 命令行逐行合并两个文件

使用 Windows 命令行逐行合并两个文件

我有一个批处理脚本,它将两个传感器收集器运行到两个单独的 csv 文件中。

我想在脚本末尾运行一个命令,逐行合并这两个文件。

即:文件1:

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

文件2

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

合并文件:

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

答案1

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

更新 1:

powershell $f1=gc File1;$f2=gc File2;$i=0;$f1^|%{$f1[$i]+','+$f2[$i];++$i}>Merged-File.txt

答案2

对于批量解决方案,您可以尝试

@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

相关内容