2

I need to sort the directories alphabetically descending and piping to sort is not working.

alias ld='ls -altp | grep ^d|sort -n'
4
  • Welcome to Unix & Linux! It is generally a really bad idea to parse the output of ls. You should probably look into either using find or simple shell globbing to get your list of files to process. Extensive further reading on the subject can be found here.
    – DopeGhoti
    Commented May 4, 2018 at 18:06
  • What's wrong with the default lexicographical ordering of the output of ls?
    – Kusalananda
    Commented May 4, 2018 at 18:11
  • OP appears to be trying to find only directories.
    – DopeGhoti
    Commented May 4, 2018 at 18:12
  • If any of the answers solved your problem, please accept it by clicking the checkmark next to it. Thank you!
    – Jeff Schaller
    Commented May 16, 2018 at 10:53

3 Answers 3

4
ls -ld */

This will give you the directories in the current directory in ls long format, in lexicographical order. If a file is a symbolic link to a directory, this will be listed as a directory too.

If you have ls aliased to something, then use command ls or \ls instead of just ls above.

The trailing slash after * will ensure that the * expands to only directories (possibly by resolving symbolic links), and it will be included in the output too. The -d option will make sure that the directories themselves are listed, not their contents.

As Jeff points out, naming your alias ld is a bad idea since it collides with the name of an existing utility.

4

Don't parse the output of ls. It's a bad idea and doing so will make you feel bad. Instead, find the directories, and let ls sort them for you without then trying to chew on its output:

$ find . -maxdepth 1 -type d -print0 | xargs -0 ls -ld

Cheerfully, ls already lexographically sorts its output by default.

More simply, there is tree:

$ tree -d -L 1
1

You're telling sort to sort the long listing of ls numerically. That's after telling ls to sort the listing by modification time (t)!

My best suggestion for a short fix would be:

ls -d */ | sort # optionally `-f` to sort upper- and lower-case together.

I'd suggest a shell such as zsh that can select directories and sort them by itself:

zsh -c "ls -ld */(on)"

Where the / specifies that you only want directories, and the (on) qualifier says to sort the list based on their name.

I would also recommend against overloading the ld program name.

alias lls='zsh -c "ls -ld */(on)"'

You must log in to answer this question.

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