specify the sort order in "copy /b *.dat foo" in Windows cmd

2

1

Normally, when I do a copy /b *.data foo in Windows cmd, the *.data files are catenated in the sorted order into the destination file foo. This matches my desired behavior.

However, I just met a curious directory in which this copy /b command will copy the files out of order. The order is not exactly random, but second last file in the sorted order will go first, followed by the remaining files in sorted order.

Is there a way to overcome this strange sorting behavior? More generally, what if I want to copy the files, say, in the reverse order?

maverickwoo

Posted 2010-12-02T02:35:07.310

Reputation: 123

What's the name of odd file? – Joel Coehoorn – 2010-12-02T02:52:19.040

@Joel The filenames are just nnnnnnnn.data where n is a digit and the numbers are consecutive counting from 1. The odd file is always the second last file in the sorted order. Say if I have 5 files, 00000004.data will come out first. – maverickwoo – 2010-12-02T05:20:08.550

Answers

2

This will concatenate the files (even the ones with spaces) in reverse order:

C:\> for /f "tokens=*" %i in ('dir /a-d /o-n /b c:\some_dir\*') do @type %i >> c:\another_dir\dest.dat

If there are only a few files, you can list them explicitly:

C:\> copy /b c.dat+a.dat+b.dat dest.dat

Something like this might work in some situations:

C:\> copy /b file*.dat+foo.dat+bar*.dat dest.dat

Paused until further notice.

Posted 2010-12-02T02:35:07.310

Reputation: 86 075

Note that % needs to be escaped as %% in a .bat file. – Cees Timmerman – 2014-10-10T09:13:59.600

I must learn to type faster! What Dennis said. Although type (or more) will only do an ASCII copy and copy /b is binary. – Rhys Gibson – 2010-12-02T04:39:12.850

@Rhys: I just tested type with binary files and it worked perfectly. – Paused until further notice. – 2010-12-02T04:47:33.293

Thank you. I was also suspicious on typing a binary file but apparently it works as expected on my Windows 7 machine. – maverickwoo – 2010-12-02T05:22:29.250

Great. I stand corrected. – Rhys Gibson – 2010-12-02T20:53:58.600