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
1.1k views
in Technique[技术] by (71.8m points)

sorting - Naturally Sort Files in Batch

I have a folder with 20 some files and am wanting to sort them similar to the way Windows Explorer does. The files I have all have prefixes of block sizes like so:

1024KB.log
32KB.log
64KB.log
4KB.log
256KB.log
512KB.log

But when I sort them in batch, it only looks at the first digit then sorts them like so:

1024KB.log
256KB.log
32KB.log
4KB.log
512KB.log
64KB.log

I want to sort them by smallest to largest block size. Any ideas?

EDIT: I also have to keep the file name integrity because I then call another script which uses the file names and creates strings.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Take Command - the CMD.EXE replacement has natural sorting.

If you can pad the filenames with zeros then a normal sort will return them ok.

This code will return them sorted numerically:

@echo off
type nul>1024KB.log
type nul>32KB.log
type nul>64KB.log
type nul>4KB.log
type nul>256KB.log
type nul>512KB.log

setlocal enabledelayedexpansion
for %%a in (*.log) do (
set num=0000000000%%a
set num=!num:~-14!
set $!num!=%%a
)
for /f "tokens=1,* delims==" %%a in ('set $0') do echo %%b
pause

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

2.1m questions

2.1m answers

60 comments

57.0k users

...