In Linux, the ls
command does not have a built-in option to sort files by type directly. However, you can use a combination of ls
with other commands to achieve a sort by file type. Here’s how you can do it:
- List files grouped by type (using
ls
with a custom format andsort
):
ls -l |awk '{print $1, $9}' |sort
- Sort by file type and then by name:
ls -l |awk '{print $1, $9}' |sort -k2
- Using
file
command to determine file type and sort:
Thefile
command can be used to get the type of each file, and thensort
can be used to organize them:
file * | sort
- Sort by file type and display only the file names:
ls -l | awk '{print $1, $9}' | sort -k2 | cut -d' ' -f2-
- Combine with
grep
to filter by specific file types (e.g., directories):
ls -l | grep '^d' | awk '{print $1, $9}' | sort -k2 | cut -d' ' -f2-
- Using
find
to sort files by type:
Thefind
command can be used to list files with their types, which can then be sorted:
find . -maxdepth 1 -printf '%T@ %p\n' | sort
In these examples:
awk '{print $1, $9}'
is used to print the file type and the file name.sort -k2
sorts based on the second column, which is the file type when usingawk
to print$1
.cut -d' ' -f2-
cuts the output to display everything after the first space, effectively showing only the file names.file *
checks each file in the current directory and prints its type.
Please note that these commands might not work perfectly in all environments, especially with different locale settings or when there are non-standard file types present. Adjustments may be needed based on the specific requirements and environment.