How to Use the ls Command to Sort Files and Directories in Linux

In Linux, the ls command sorts files and directories by name in alphabetical order by default. Here are some examples of how to use ls to sort by name:

  1. Sort by name (default behavior):
   ls
  1. Sort by name in reverse order (z to a):
   ls -r
  1. Combine with long format listing to show detailed information about files while sorting by name:
   ls -l
  1. Sort by name and show only directories:
   ls -ld */ | cut -d' ' -f2-
  1. Sort by name and show only files (excluding directories):
   ls -l | grep -v '^d'
  1. Sort by name and exclude certain patterns (e.g., hiding directories):
   ls -l | grep -v '^d' | grep -v 'pattern_to_exclude'
  1. Sort by name and show human-readable file sizes:
   ls -lh
  1. Sort by name and show inode number:
   ls -li
  1. Sort by name and display files with detailed information including modification time:
   ls -lt
  1. Sort by name and display only the basename of files (excluding directories):
    bash ls -l | awk '{if ($1 ~ /^[^d]./) print $9}'

Remember that the -r option reverses the sort order when used with ls. The grep -v '^d' pattern is used to exclude directories when listing files, and it can be adjusted for different filters. The awk command in the last example is used to print only the file names (the 9th column in the ls -l output) that do not start with ‘d’ (which indicates a directory in the first column of ls -l output).

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