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:
- Sort by name (default behavior):
ls
- Sort by name in reverse order (z to a):
ls -r
- Combine with long format listing to show detailed information about files while sorting by name:
ls -l
- Sort by name and show only directories:
ls -ld */ | cut -d' ' -f2-
- Sort by name and show only files (excluding directories):
ls -l | grep -v '^d'
- Sort by name and exclude certain patterns (e.g., hiding directories):
ls -l | grep -v '^d' | grep -v 'pattern_to_exclude'
- Sort by name and show human-readable file sizes:
ls -lh
- Sort by name and show inode number:
ls -li
- Sort by name and display files with detailed information including modification time:
ls -lt
- 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).