How can I sort ls by owner and group?

Solution 1:

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.

Solution 2:

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.