2

Is it possible in the command line to have the same sort order for files/folders as Finder. If I run find . -type d, I get as output:

./Folder 1
./Folder 10
./Folder 11
./Folder 2
./Folder 3
...

I tried find -s . -type d, and also added some sort options. No luck.

What I want is this:

./Folder 1
./Folder 2
./Folder 3
...
./Folder 10
./Folder 11
1
  • 2
    Is there a specific reason why you use find instead of ls?
    – nohillside
    Dec 29, 2016 at 10:05

2 Answers 2

2

If you look at what find says about sorting:

 -s   Cause find to traverse the file hierarchies in 
lexicographical order, i.e., alphabetical order within each directory.  
Note: `find -s` and `find | sort` may give different results.

This means we need to pipe it to sort so that we can manipulate it a bit more.

As you have already seen, a simple alphanumeric sort won't work because it's comparing everything as an ANSI character not as numbers. What we need to do is just compare the numbers. We can do this with the -k option of sort

find . -type d | sort -k2.3

What the sort -k2.3 command is doing is sorting on the second field (delimited by the space) ending at the 3rd position. This is the result using your folder naming convention1:

.
./Folder 1
./Folder 2
./Folder 3
./Folder 4
./Folder 5
./Folder 6
./Folder 7
./Folder 8
./Folder 9
./Folder 10
./Folder 11
./Folder 12
./Folder 13
./Folder 14
./Folder 15

1 To create this folder structure, I used the command in my home folder:

mkdir test; cd test; for n in {1..15}; do mkdir "Folder $n"; done
1
  • Thanks, I didn't know the -k option. However, that didn't meet my requirements. I made this small python program to solve this problem.
    – doekman
    Dec 30, 2016 at 15:35
0

Can also do

ls -v

which sorts files by version numbers in names by natural order.

From man ls

-v     natural sort of (version) numbers within text
2
  • 2
    macOS does not come with GNU ls installed.
    – fd0
    Dec 29, 2016 at 20:35
  • 1
    GNU ls can be installed via Homebrew.
    – nohillside
    Dec 30, 2016 at 12:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .