Skip to main content

bash - How to sort first directories then files etc… when using “ls” in Unix


I would like to use the ls command to first show directories and then files. I tried:


ls -la | sort -k 1

But I got a wrong order.



Answer



The following command will list directories first, ordinary files second, and links third.


ls -la | grep "^d" && ls -la | grep "^-" && ls -la | grep "^l"


Also, it would make a great deal of sense to create an alias for this command to save keystrokes.


Edit:


If you want directories first, and then everything that is not a directory second, use this:


ls -la | grep "^d" && ls -la | grep -v "^d"


Comments