use*_*064 3 cmd file batch-file
是否可以同时迭代多个文件的行?我需要通过连接两个不同文件中的行来输出文件(并添加一些额外的单词).
我知道CMD命令:
FOR %variable IN (set) DO command [command-parameters]
Run Code Online (Sandbox Code Playgroud)
但是,如果您需要同时迭代两个文件,这无济于事.更准确地说,我需要以下内容:
While the first file is not ended
line1 <- READ a line from the first file
line2 <- READ a line from the second file
WRITE on a third file line1 + line2
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种方法来完成我之前在dos批处理文件中描述的内容.谢谢!
我知道3种基本技术,可以从中衍生出大量的混合动力.
选项1(此选项与wmz解决方案非常相似)
使用FOR/F读取文件1,使用SKIP选项读取带有第二个FOR/F的文件2.必须在CALLed子例程中读取文件2,以便可以在不中断文件1循环的情况下中断循环.
限制:
;由于默认的EOL选项,将不会读取以...开头的行.如有必要,可以通过将EOL设置为新行字符来解决此问题.请参阅如何:FOR/F禁用EOF或使用报价作为分隔由于CALL,此选项很慢,因为每行必须读取第二个文件一次.
编辑 - 固定的代码如果第二个文件提前结束仍然输出一行
@echo off
setlocal disableDelayedExpansion
set "file1=a.txt"
set "file2=b.txt"
set "out=out.txt"
set /a cnt=0
set "skip="
>"%out%" (
for /f "usebackq delims=" %%A in ("%file1%") do (
set "found="
call :readFile2
if not defined found (echo %%A - )
)
)
type "%out%"
exit /b
:readFile2
for /f "usebackq %skip% delims=" %%B in ("%file2%") do (
set found=1
echo %%A - %%B"
goto :break
)
:break
set /a cnt+=1
set "skip=skip=%cnt%"
exit /b
Run Code Online (Sandbox Code Playgroud)
选项2
此选项通过使用FINDSTR为每行添加行号后跟冒号来解决空行问题.FINDSTR用于仅读取文件2中的第n行,因此无需中断第二个循环.
限制:
此选项甚至比选项1慢
编辑 - 固定的代码如果第二个文件提前结束仍然输出一行
@echo off
setlocal disableDelayedExpansion
set "file1=a.txt"
set "file2=b.txt"
set "out=out.txt"
>"%file2%.tmp" findstr /n "^" "%file2%"
>"%out%" (
for /f "tokens=1* delims=:" %%A in ('findstr /n "^" "%file1%"') do (
set "found="
for /f "tokens=1* delims=:" %%a in ('findstr "^%%A:" "%file2%.tmp"') do (
set found=1
echo %%B - %%b
)
if not defined found (echo %%B - )
)
)
del "%file2%.tmp"
type "%out%"
Run Code Online (Sandbox Code Playgroud)
选项3
使用SET/P读取这两个文件.FIND用于获取文件1中行数的计数,因为SET/P无法区分空行和文件结尾.
此选项消除了许多限制和复杂性,但引入了自身的局限性.
限制:
<CR><LF>.Unix风格<LF>不起作用.这个选项是迄今为止最快的.只要限制是可接受的,它是优选的.
@echo off
setlocal enableDelayedExpansion
set "file1=a.txt"
set "file2=b.txt"
set "out=out.txt"
for /f %%N in ('type "%file1%"^|find /c /v ""') do set "cnt=%%N"
>"%out%" 9<"%file1%" <"%file2%" (
for /l %%N in (1 1 %cnt%) do (
set "ln1="
set "ln2="
<&9 set /p "ln1="
set /p "ln2="
echo !ln1! - !ln2!
)
)
type "%out%"
Run Code Online (Sandbox Code Playgroud)