4

I have a large number of files and directories in one directory.

I need to sort them in terms of the permissions.

For example

drwx------
drwxr-xr-x 
drwxr-x---

I am just wondering if we can sort the files and dirs using ls?

1
  • 1
    ls -l|sort will sort by permissions. Commented Oct 31, 2014 at 12:22

2 Answers 2

11

ls does not directly support sorting by permissions, but you can combine it with the sort command:

ls -l | sort

You can use the -k option to sort to start matching from a specific character, the format is -k FIELD.CHAR, the permissions are the first field in the ls output. So e.g. -k 1.2 will start from the second character of the permission string, which will ignore any directory / device / link etc. flag, or -k 1.5 for sorting by group permissions.

If you don't want the additional output of ls -l, you can remove it with awk:

 ls -l | sort | awk '{ print $1, $NF}'

This will print only the first field (the permissions) and the last one (the filename).

1
  • 1
    If you don't want additional output it much easy to use stat command stat -c"%A %n" * | sort Commented Oct 31, 2014 at 15:28
2

You can also sort by octal value.

for i in *; do stat --format="%a %n" "$i"; done | sort -n

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.