linux ls sort by type

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:

  1. List files grouped by type (using ls with a custom format and sort):
   ls -l |awk '{print $1, $9}' |sort
  1. Sort by file type and then by name:
   ls -l |awk '{print $1, $9}' |sort -k2
  1. Using file command to determine file type and sort:
    The file command can be used to get the type of each file, and then sort can be used to organize them:
   file * | sort
  1. Sort by file type and display only the file names:
   ls -l | awk '{print $1, $9}' | sort -k2 | cut -d' ' -f2-
  1. 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-
  1. Using find to sort files by type:
    The find 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 using awk 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.

This entry was posted in Linux File & Directory, Linux Ls and tagged , , . Bookmark the permalink.