How can I sort ls by owner and group?

9

5

How can I list directories with ls and sort them by their owner and group?

AnnanFay

Posted 2010-05-14T09:01:33.353

Reputation: 626

Answers

8

Try this:

ls -l | awk '{print $3, $4, $8}' | sort

It will print the user name, the group name and the file name, provided that the file name doesn't contain spaces. Alternatively, you can type:

ls -l | awk '{print $3, $4, $0}' | sort

This will print the user name, group name and the full ls -l output, sorted by the user name first, then the group name, then whatever ls -l prints first.

Note that depending on your distribution, the actual column numbers may differ. I tried mine in SUSE and coreutils version 5.2.1.

There are probably better, more elaborate solutions, but this is the simplest one, and will work most of the time.

petersohn

Posted 2010-05-14T09:01:33.353

Reputation: 2 554

1s/row numbers/column numbers/ – Paused until further notice. – 2010-05-14T11:20:21.170

7

As petersohn said, something similar to:

  • ls -l | awk '{print $3, $4, $8, $0}' | sort | column -t
    added the $8 and the column -t for pretty print

Or even better:

  • ls -l | sort -k 3 - sorts by owner and by default sorts the next field (group) and on
  • ls -l | sort -k 4,4 -k 3 - sorts by group and then by owner
  • ls -l | sort -k 3,3 -k 8 - sorts by owner and then by filename

Note: the comma is the terminator field so 3,3 starts and end at field 3 3,5 sorts from fields 3 to 5.

vol7ron

Posted 2010-05-14T09:01:33.353

Reputation: 403

To sort by group and then by owner I had to add -b to ignore leading blanks, otherwise the list would be sorted by the string length of the owner name. – Stefan Schmidt – 2013-05-27T20:22:54.153