Is there a way to order directories using Julia's readdir()?

Viewed 137

I have over thousand files named LOGS_A1, LOGS_A2, LOGS_A3, ..., LOGS_A16281`, and I want to list out the files in that order

cwd = pwd()
ParentDir = joinpath(cwd,"LOGS_A")
dirs = readdir(ParentDir, join=true, sort=true)

However, it is ordering the entries alphabetically:

LOGS_A999
LOGS_A9990
LOGS_A9991
LOGS_A9992
LOGS_A9993
LOGS_A9994
LOGS_A9995
LOGS_A9996
LOGS_A9997
LOGS_A9998
LOGS_A9999

Is there a way to sort it so it is listed from 1 to 16281?

2 Answers

For a simpler and more robust answer, use NaturalSort.jl:

julia> using Pkg; pkg"add NaturalSort"
  Resolving package versions...
Updating `~/.julia/environments/v1.5/Project.toml`
  [c020b1a1] + NaturalSort v1.0.0
Updating `~/.julia/environments/v1.5/Manifest.toml`
  [c020b1a1] + NaturalSort v1.0.0

julia> using NaturalSort
[ Info: Precompiling NaturalSort [c020b1a1-e9b0-503a-9c33-f039bfc54a85]

julia> src = ["LOGS_A1","LOGS_A10","LOGS_A11","LOGS_A2","LOGS_A3","LOGS_A4",
              "LOGS_A5","LOGS_A6","LOGS_A7","LOGS_A8","LOGS_A9"];

julia> sort(src, lt=natural)
11-element Array{String,1}:
 "LOGS_A1"
 "LOGS_A2"
 "LOGS_A3"
 "LOGS_A4"
 "LOGS_A5"
 "LOGS_A6"
 "LOGS_A7"
 "LOGS_A8"
 "LOGS_A9"
 "LOGS_A10"
 "LOGS_A11"

Is this what you want?

julia> src = ["LOGS_A1",
              "LOGS_A10",
              "LOGS_A11",
              "LOGS_A2",
              "LOGS_A3",
              "LOGS_A4",
              "LOGS_A5",
              "LOGS_A6",
              "LOGS_A7",
              "LOGS_A8",
              "LOGS_A9"];

julia> sort(src, by = x -> parse(Int, chop(x, head=6, tail=0)))
11-element Array{String,1}:
 "LOGS_A1"
 "LOGS_A2"
 "LOGS_A3"
 "LOGS_A4"
 "LOGS_A5"
 "LOGS_A6"
 "LOGS_A7"
 "LOGS_A8"
 "LOGS_A9"
 "LOGS_A10"
 "LOGS_A11"

I use chop as in this case it seems simplest since I understand that you have the same prefix everywhere.

An alternative is:

julia> src[sortperm(parse.(Int, chop.(src, head=6, tail=0)))]
11-element Array{String,1}:
 "LOGS_A1"
 "LOGS_A2"
 "LOGS_A3"
 "LOGS_A4"
 "LOGS_A5"
 "LOGS_A6"
 "LOGS_A7"
 "LOGS_A8"
 "LOGS_A9"
 "LOGS_A10"
 "LOGS_A11"

which is slightly faster, but more complex to write (and probably in your use case speed does not matter).

Related