1

i wanted to copy files "scholar (1).txt" to "scholar (25).txt" to a single .txt file used the following methods: wikihow: Merge Text (.Txt) Files in Command Prompt

for %f in (*.txt) do type "%f" >> output.txt

SU: is there a way to combine text files using the windows command line?

copy *.txt bigfile.txt

also type *.js > all.txt

but all files are not copied in sequential manner:

`C:\..\Documents\New folder>type *.txt >all.txt

 scholar (1).txt
 scholar (10).txt
 scholar (11).txt
 scholar (12).txt
 scholar (13).txt
 scholar (14).txt
 scholar (15).txt
 scholar (16).txt
 scholar (17).txt
 scholar (18).txt
 scholar (19).txt
 scholar (2).txt
 scholar (20).txt
 scholar (21).txt
 scholar (22).txt
 scholar (23).txt
 scholar (24).txt
 scholar (25).txt
 scholar (3).txt
 scholar (4).txt
 scholar (5).txt
 scholar (6).txt
 scholar (7).txt
 scholar (8).txt
 scholar (9).txt`
2
  • Too bad that sort doesn't seem to have an option to sort numerically. Sep 6, 2014 at 18:20
  • To clarify what’s happening, the files are being copied in sequential order, just not in numerical order. Windows Explorer has learned how to sort in numerical order in the past decade or two, but Command Prompt still uses lexicographical order; i.e., dictionary order. Just as the words “ha”, “he”, “hi”, and “ho” come before the word “I”, so the numbers 10, 11, 12,…, 19 are sorted before 2. If you could rename your 1, 2, 3, …, 9 files to be named 01, 02, 03, …, 09, it would work. Sep 6, 2014 at 19:53

1 Answer 1

1
(for /l %a in (1 1 25) do @type "scholar (%a).txt")>all.txt

For usage inside a batch file, percent signs need to be doubled, replacing % with %%

If the total number of files is unknown, but the files are named as indicated, this code can be used

@echo off
    setlocal enableextensions disabledelayedexpansion

    for %%z in ("scholar (*).txt") do for /f "tokens=2 delims=()" %%a in ("%%~nxz") do (
        set /a "num=1000000000+%%a"
        setlocal enabledelayedexpansion
        for %%b in (!num!) do endlocal & set "f[%%b]=%%~fz"
    )
    (for /f "tokens=1,* delims==" %%a in ('2>nul set f[') do type "%%b") > all.txt

This creates an array in environment that allows us to retrieve a properly numerical sorted list of the files.

2
  • Nice idea, but... "Environment variable f[ not defined" Jan 28, 2016 at 13:51
  • 1
    @MicheldeRuiter, you can avoid the error mesage (now included in code), but the reason for it is that not matching files have been found
    – MC ND
    Jan 28, 2016 at 16:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .