Home » Questions » Computers [ Ask a new question ]

How to make ls sort by file extension and then name?

How to make ls sort by file extension and then name?

By default the ls command sorts just by filename, but I want directories to appear before other file types. I might even want files to be sorted by extension, like the way Windows explorer sorts by the type column. Is there a way to do something similar with ls?

Asked by: Guest | Views: 53
Total answers/comments: 5
Guest [Entry]

"I think the complete answer is more of a combination of the above.

-X (later --sort=extension) has been supported in Linux since at least FC3 and will sort based on extension. --group-directories-first was added more recently (maybe around FC8?). However, combining the two doesn't seem to work (at least on FC8).

The primary issue seems to be with the use of singular primary sort keys. See this mailing list discussion for some insight into it."
Guest [Entry]

"-X is the option you're looking for:

ls -lX"
Guest [Entry]

"If you're not on linux,

ls -l |sort -d -k 1.1,1.1r -k 9 |awk '{print $9}'

should sort directories first (let me know if I'm wrong). Doesn't sort by extension, though: you have to make the awk statement a lot busier if you want to do that ...

To also make it work with names containing spaces, I would probably replace the awk with something like sed -E -e 's/([^ ]+[ ]+){8}//' to strip out the first 8 fields instead of printing the 9th"
"If you're not on linux,

ls -l |sort -d -k 1.1,1.1r -k 9 |awk '{print $9}'

should sort directories first (let me know if I'm wrong). Doesn't sort by extension, though: you have to make the awk statement a lot busier if you want to do that ...

To also make it work with names containing spaces, I would probably replace the awk with something like sed -E -e 's/([^ ]+[ ]+){8}//' to strip out the first 8 fields instead of printing the 9th"
Guest [Entry]

"I added to my .bashrc (linux) the line

alias lx = ""ls -X""

that way I just type lx and get it sorted by extension."
Guest [Entry]

"A good approach is separating folders at first, then the sorted files by extensions, by SORTING and REVERSING out:

ls -p | grep /;ls -p | grep -v / | rev | sort | rev"