I have a text file, it contains lines, I need to swap even and odd lines. I took even and odd lines and wrote them into separate files.

@echo off setlocal EnableDelayedExpansion set "filepath1=C:\\Users\\andyb\\Desktop\\testfile.txt" set "filepath2=C:\\Users\\andyb\\Desktop\\testfile2.txt" set "filepath3=C:\\Users\\andyb\\Desktop\\testfile3.txt" set counter=0 set B=0 for /F %%A in (%filepath1%) do ( set /a B=!counter!%%2 if !B! equ 0 (echo %%A>>%filepath2%) else (echo %%A>>%filepath3%) set /A counter=counter+1 ) 

Now I need to take one line from a file with odd lines, then one line from a file with even lines and write it into a separate file, I just can’t figure out how to implement this in the loop, since the loop variable is assigned one value from one file, I need to take a line from two files for one iteration.

  • Why not do everything in one step from the source file testfile.txt ? Please edit your query and add sample input and output; you must follow the rule of minimal reproducible example . - JosefZ

1 answer 1

No need to use additional files. Work with one

 @echo off setlocal EnableDelayedExpansion set in_file=1.txt set out_file=2.txt rem //Строка, которая никогда не встретится в файле set null="$$$$$" rem //Предыдущая строка set prev=%null% for /F "tokens=*" %%A in (%in_file%) do ( if "!prev!" == "%null%" ( rem //Если предыдущая строка пустая, то присваиваем текущую set prev=%%A ) else ( rem //Иначе выводим текущую строку echo %%A>>%out_file% rem //выводим предыдущую строку echo !prev!>>%out_file% rem //Очищаем предыдущую строку set prev=%null% ) ) rem //Если в файле нечетное количество строк, то выводим предыдущую строку if not "!prev!" == "%null%" echo !prev!>>%out_file%