Natural Order

Natural ordering of files is to have file1.txt, file2.txt and file10.txt in this order rather than the lexicographic default file1.txt, file10.txt and file2.txt.

The "concept" and further discussions can be found here and here.

What I personally do is to recourse to the following Mathematica piece of code to physically rename the files as 01--file1.txt, 02--file2.txt and 03--file10.txt, so that lexicographic order enforces natural ordering.

The code is given below:

(* ::Package:: *)
 
NaturalOrder=#[[Ordering[Abs[ToExpression[StringCases[#,NumberString]]]]]]&;
 
 
RenameNaturalOrder[listfiles_]:=Module[{ol,lol,lnum,lmx,lpad},
ol=NaturalOrder[listfiles];
lol=Length[ol];
lnum=ToString/@Range[lol];
lmx=StringLength[lnum[[-1]]];
lpad=Table[StringJoin@@Table["0",{i,lmx-StringLength[lnum[[j]]]}],{j,lol}];
StringJoin@@#&/@Transpose[{lpad,lnum,Table["-",{i,lol}],ol}]]
 
 
RenameFilesNaturalOrder[listOfFiles_]:=MapThread[RenameFile,{NaturalOrder[listOfFiles],RenameNaturalOrder[listOfFiles]}]
 
 
directive=Import["/home/laussy/comp/mathematica/from-shell/natural-order.dat"];
 
 
SetDirectory[directive[[1,1]]];
 
 
If[Length[directive]==2,
filter=directive[[2,1]],
filter="*"
];