内容文件A1
的:文件A2
的批处理脚本合并两个文件的行到第三个文件
AA
VV
BB
内容:
DD
EE
FF
我想要的A1
和A2
内容合并为在A3
之下,因此A3
的预期数据为:
AADD
VVEE
BBFF
另外,在A3
预期的输出可能是:
AA is from DD
VV is from EE
BB is from FF
感谢您的帮助。在我发布之前,我尝试过搜索并找不到已发布类似内容的人...
内容文件A1
的:文件A2
的批处理脚本合并两个文件的行到第三个文件
AA
VV
BB
内容:
DD
EE
FF
我想要的A1
和A2
内容合并为在A3
之下,因此A3
的预期数据为:
AADD
VVEE
BBFF
另外,在A3
预期的输出可能是:
AA is from DD
VV is from EE
BB is from FF
感谢您的帮助。在我发布之前,我尝试过搜索并找不到已发布类似内容的人...
我们可以将文件的内容加载到批量变量数组所以每个其行可直接访问任何你想:
@echo off
setlocal EnableDelayedExpansion
rem Load first file into A1 array:
set i=0
for /F "delims=" %%a in (A1.txt) do (
set /A i+=1
set A1[!i!]=%%a
)
rem Load second file into A2 array:
set i=0
for /F "delims=" %%a in (A2.txt) do (
set /A i+=1
set A2[!i!]=%%a
)
rem At this point, the number of lines is in %i% variable
rem Merge data from both files and create the third one:
for /L %%i in (1,1,%i%) do echo !A1[%%i]! is from !A2[%%i]!>> A3.txt
编辑替代解决方案
还有另一种方法可以做到不使用批量变量,因此可以在任何大小的文件上使用,尽管速度较慢。我借用了Andy Morris在其解决方案中使用的方法:1-在两个文件中插入行号,2-将两个文件合并为一个文件,3-对合并文件进行排序,以及4-将行合并到同一行中。下面的程序基本上是Andy的一个,有几个小修改使其更快(修正了一个微妙的错误)。
@echo off
setlocal EnableDelayedExpansion
call :AddLineNumbers A1.txt A > Both.txt
call :AddLineNumbers A2.txt B >> Both.txt
sort Both.txt /O Sorted.txt
echo EOF: >> Sorted.txt
call :creatNewLines <Sorted.txt> Result.txt
goto :eof
:AddLineNumbers
findstr /n ^^ %1 > tem.tmp
for /f "tokens=1* delims=:" %%a in (tem.tmp) do (
set /a lineNo=1000000+%%a
echo !lineNo!%2:%%b
)
goto :eof
:creatNewLines
set /p lineA1=
for /f "tokens=1* delims=:" %%a in ("%lineA1%") do (
if %%a == EOF goto :eof
set /p dummy=%%b< nul
)
set /p lineA2=
for /f "tokens=1* delims=:" %%a in ("%lineA2%") do echo is from %%b
goto creatNewLines
根据其内容排序命令行。 Andy的原始方法可能会失败,因为在行号之后,根据行内容对行进行排序,因此每个文件的行可能会错位。在这种方法中,在行号后添加一个附加字符(A或B),这样每个文件的行总是放在正确的位置。
这样做的好方法,可能会让大文件变得有趣。从http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds_shelloverview.mspx?mfr=true,所有变量的最大总环境变量大小,其中包括变量名称和等号,为65,536KB。但可能更快的速度达到此限制 –
关于排序行的顺序的好处。不知道我打算优化,但你有一些有趣的技术。 –
如果使用linux,我会推荐使用剪切和粘贴(命令行)。查看手册页。
或者,如果您不需要自动化,则可以使用vim块模式剪切和粘贴。使用control-v进入块模式可视模式。
如果你的原始数据是DATA1.TXT和Data2.txt这应该这样做:
@echo off
call :AddLineNumbers data1.txt Tem1.txt
call :AddLineNumbers data2.txt Tem2.txt
copy tem1.txt + tem2.txt tem3.txt
sort <tem3.txt> tem4.txt
call :GetDataOut tem4.txt > tem5.txt
set OddData=
for /f %%a in (tem5.txt) do call :creatNewLines %%a
goto :eof
:AddLineNumbers
find /v /n "xx!!xx" < %1 > tem.txt
call :ProcessLines > %2
goto :eof
:ProcessLines
for /f "tokens=1,2 delims=[]" %%a in (tem.txt) do call :EachLine %%a %%b
goto :eof
:eachLine
set LineNo=00000%1
set data=%2
set LineNo=%LineNo:~-6%
echo %LineNo% %data%
goto :eof
:GetDataOut
for /f "tokens=2" %%a in (%1) do @echo %%a
goto :eof
:creatNewLines
if "%oddData%"=="" (
set oddData=%1
) else (
echo %oddData% %1
set oddData=
)
goto :eof
你的方法有一个小错误。查看我答案中的最后一段... – Aacini
这不是“将多个文件复制到一个文件”。它是“将两个文件的行合并成第三个文件”。 –