![使用 Windows 命令行逐行合并两个文件](https://linux22.com/image/1425010/%E4%BD%BF%E7%94%A8%20Windows%20%E5%91%BD%E4%BB%A4%E8%A1%8C%E9%80%90%E8%A1%8C%E5%90%88%E5%B9%B6%E4%B8%A4%E4%B8%AA%E6%96%87%E4%BB%B6.png)
我有一个批处理脚本,它将两个传感器收集器运行到两个单独的 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