1

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

alias ld='ls -altp | grep ^d|sort -n'
Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
user289335
  • 21
  • 2
  • 2
  • 4
  • Welcome to Unix & Linux! It is generally a [really bad idea](http://mywiki.wooledge.org/ParsingLs) 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](https://unix.stackexchange.com/questions/128985/why-not-parse-ls). – DopeGhoti May 04 '18 at 18:06
  • What's wrong with the default lexicographical ordering of the output of `ls`? – Kusalananda May 04 '18 at 18:11
  • OP appears to be trying to find only _directories_. – DopeGhoti May 04 '18 at 18:12
  • If any of the answers solved your problem, please [accept it](https://unix.stackexchange.com/help/someone-answers) by clicking the checkmark next to it. Thank you! – Jeff Schaller May 16 '18 at 10:53

3 Answers3

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
Hayden Schiff
  • 908
  • 1
  • 6
  • 12
DopeGhoti
  • 73,792
  • 8
  • 97
  • 133
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.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
0

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)"'
Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250