Merge .txt files in Specific Order
@echo off
cd /d "%~dp0" && set "_c=10000" && setlocal enabledelayedexpansion
for /l %%L in (1 1 300)do for /f tokens^=1* %%i in ('%__AppDir__%where.exe .:Chapter?%%~L.txt')do (
set /a "_c+=1" && call set "_new=Chapter !_c:~-4!.txt" && rename ".\Chapter?%%~L.txt" "!_new!")
for /f tokens^=* %%i in ('%__AppDir__%where.exe .:Chapter*.txt')do echo;>>"%%~dpnxi"
copy ".\Chapter*.txt" ".\newfile.txt" & endlocal
- You can
.\rename
your files to an order that meets an alphanumeric, not just numeric, sequence.
1. Replace with the full path of the folder where you have your files.
cd /d "%~dp0" cd /d "D:\Full\Path\To\Folder
2. Use a loop to get the order in which you go from 1 to 300 (1 in 1 incrementing by 1).
for /l %%L in (1 1 300)do ...
3. A pre-defined variable with 2 extra digits to give us the 1 or more lead zeros, incrementing inside the loop to use when renaming, only the last 4 digits.
set "_c=10000"
set /a "_c+=1" && call set "_new=Chapter !_c:~-4!.txt"
4. An additional for /F
loop will list each file in the correct order obeying the for /L
loop also in order 1 to 300.
for /f tokens^=1* %%i in ('%__AppDir__%where.exe .:Chapter?%%~L.txt')do
5. With the variable incremented in the loop, use substring to rename your files m led by zeros
:: Original Name <==> New File Name
:: -----------------------------------------
:: Chapter 1.txt <==> Chapter 0001.txt
:: Chapter 10.txt <==> Chapter 0010.txt
:: Chapter 100.txt <==> Chapter 0100.txt
set "_c=10000"
set /a "_c+=1" && call set "_new=Chapter !_c:~-4!.txt"
rename ".\Chapter?%%~L.txt" "!_new!"
6. When the executions of the double loop are finished, execute use echo
to add the extra line at end of each of your files...
for /f tokens^=* %%i in ('%__AppDir__%where.exe .:Chapter*.txt')do echo;>>"%%~dpnxi"
7. After all the above processing, you are ready to execute your command and get the desired result:
copy ".\Chapter*.txt" ".\newfile.txt"
-
Obs.: I don't know what encode your files are, but I suppose a
/b
inary copy doesn't overwrite the last line.
@echo off
cd /d "%~dp0" && set "_c=10000" && setlocal enabledelayedexpansion
for /l %%L in (1 1 300)do for /f tokens^=1* %%i in ('%__AppDir__%where.exe .:Chapter?%%~L.txt')do (
set /a "_c+=1" && call set "_new=Chapter !_c:~-4!.txt" && rename ".\Chapter?%%~L.txt" "!_new!")
copy /b ".\Chapter*.txt" ".\newfile.txt" & endlocal
Additional Resources:
Set /?
For /?
For /L /?
For /F /?
Set variable=variable:substrings
| DOS - String Manipulation
Copy the batch to the folder where the txt files are and execute:
@echo off
:: Set the name of the new concatenated file here:
set NewFile=NewFile.txt
If not exist "%NewFile%" copy NUL "%NewFile%"
for /L %%a in (1,1,300) do If exist "%Chapter %%a.txt" copy "%NewFile%" + "Chapter %%a.txt"& echo.>>"%NewFile%" &echo.>>"%NewFile%"