2
是否有一種簡單且性能良好的方法可以逐行讀取兩個(甚至更多)文本文件?所以要有一個循環,在每次迭代中讀取每個文本文件的一行。如何通過批處理文件並行讀取兩個文本文件?
A for /F
循環中給出的多個文件不能使用,因爲這會讀取一個接一個的文件。嵌套這樣的循環當然沒有意義。
是否有一種簡單且性能良好的方法可以逐行讀取兩個(甚至更多)文本文件?所以要有一個循環,在每次迭代中讀取每個文本文件的一行。如何通過批處理文件並行讀取兩個文本文件?
A for /F
循環中給出的多個文件不能使用,因爲這會讀取一個接一個的文件。嵌套這樣的循環當然沒有意義。
訣竅是用STDINredirection<
(也參見this site)使用未定義手柄(3
到9
),用於文件讀出整個代碼塊,則該命令set /P
在塊實際讀取一行和0<&
到將未定義的手柄重定向回STDIN對於set /P
,因此用於相應的行讀取。
這裏是如何工作的例子:
假設有以下兩個文本文件names.txt
...:
Black Blue Green Aqua Red Purple Yellow White Grey Brown
...和... values.txt
:
0 1 2 3 4 5 6 7
...而我們的目標是通過線把它們結合起來線實現這個文件,names=values.txt
...:
Black=0 Blue=1 Green=2 Aqua=3 Red=4 Purple=5 Yellow=6 White=7
...下面的代碼實現了這個(見所有解釋評論,rem
):
@echo off
setlocal EnableExtensions EnableDelayedExpansion
rem // Define constants here:
set "FILE1=names.txt"
set "FILE2=values.txt"
set "RET=names=values.txt" & rem // (none to output to console)
if not defined RET set "RET=con"
rem /* Count number of lines of 1st file (2nd file is not checked);
rem this is necessary to know when to stop reading: */
for /F %%C in ('^< "%FILE1%" find /C /V ""') do set "NUM1=%%C"
rem /* Here input redirection is used, each file gets its individual
rem (undefined) handle (that is not used by the system) which is later
rem redirected to handle `0`, `STDIN`, in the parenthesised block;
rem so the 1st file data stream is redirected to handle `4` and the
rem 2nd file to handle `3`; within the block, as soon as a line is read
rem by `set /P` from a data stream, the respective handle is redirected
rem back to `0`, `STDIN`, where `set /P` expects its input data: */
4< "%FILE1%" 3< "%FILE2%" > "%RET%" (
rem // Loop through the number of lines of the 1st file:
for /L %%I in (1,1,%NUM1%) do (
set "LINE1=" & rem /* (clear variable to maintain empty lines;
rem `set /P` does not change variable value
rem in case nothing is entered/redirected) */
rem // Change handle of 1st file back to `STDIN` and read line:
0<&4 set /P "LINE1="
set "LINE2=" & rem // (clear variable to maintain empty lines)
rem // Change handle of 2nd file back to `STDIN` and read line:
0<&3 set /P "LINE2="
rem /* Return combined pair of lines (only if line of 2nd file is
rem not empty as `set /P` sets `ErrorLevel` on empty input): */
if not ErrorLevel 1 echo(!LINE1!=!LINE2!
)
)
endlocal
exit /B
是的,已經使用這種方法[這裏](http://stackoverflow.com/questions/32738831/extracting-all-lines-from-multiples-files/32739680#32739680) ,或[這裏](http://stackoverflow.com/questions/14521799/comb inining-multiple-text-files-into-one/14523100#14523100)或[這裏](http://stackoverflow.com/questions/28850167/solved-merge-several-csv-file-side-by-side-使用批處理文件/ 28864990#28864990)或[這裏](http://stackoverflow.com/questions/32238565/windows-batch-file-combine-csv-in-a-folder-by-column/32254700# 32254700)或[這裏](http://www.dostips.com/forum/viewtopic.php?f=3&t=3126)... – Aacini
@Aacini,感謝您的聯繫!我似乎在這裏使用了錯誤的搜索條件(_parallel_,_simultaneous_,_concurrent _,...);這裏僅以_combining_文件爲例... – aschipfl