Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
630 views
in Technique[技术] by (71.8m points)

sorting - Loop through files in a numeric order (Like on Windows Explorer)

I have a group of files that I want to be sorted numerically with FOR command like this:

FOR %%G IN (*.pdf) DO (
ECHO %%G
)

Is there any way to have :

1.pdf
2.pdf
3.pdf
...
10.pdf
11.pdf

Instead of :

1.pdf
10.pdf
11.pdf
12.pdf
...
2.pdf
21.pdf

Like they are ordered on the Windows Explorer? My files ordered on Windows Explorer

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
@echo off
setlocal

echo Unsorted:
for %%A in (*.pdf) do echo %%A

echo.
echo Sorted:
(
    for %%G in (*.pdf) do @(
        set "file=          %%~G"
        call set "file=%%file:~-14%%"
        call echo %%file%%
    )
) | for /f "tokens=*" %%A in ('sort') do @echo %%A

Pads each filename with 10 spaces and then trims to last 14 characters which should be within the 32 bit number range. It is piped to a for loop to sort which gets them in order like explorer. The tokens=* option removes the leading spaces. call set and call echo expands the doubled percentage variables inside a code block which saves using delayed expansion.

Output:

Unsorted:
1.pdf
11.pdf
2.pdf
22.pdf

Sorted:
1.pdf
2.pdf
11.pdf
22.pdf

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...