Question
Can you sort an ls listing by name?
Solution
My ls sorts by name by default. What are you seeing?
man ls
states:
List information about the FILEs (the current directory by default). Sort entries alpha‐betically if none of -cftuvSUX nor --sort is specified.
:
OTHER TIPS
For something simple, you can combine ls with sort. For just a list of file names:
ls -1 | sort
To sort them in reverse order:
ls -1 | sort -r
ls
from coreutils
performs a locale-aware sort by default, and thus may produce surprising results in some cases (for instance, %foo
will sort between bar
and quux
in LANG=en_US
). If you want an ASCIIbetical sort, use
LANG=C ls
The beauty of *nix tools is you can combine them:
ls -l | sort -k9,9
The output of ls -l
will look like this
-rw-rw-r-- 1 luckydonald luckydonald 532 Feb 21 2017 Makefile
-rwxrwxrwx 1 luckydonald luckydonald 4096 Nov 17 23:47 file.txt
So with 9,9
you sort column 9
up to the column 9
, being the file names. You have to provide where to stop, which is the same column in this case. The columns start with 1
.
Also, if you want to ignore upper/lower case, add --ignore-case
to the sort command.
NOTICE: "a" comes AFTER "Z":
$ touch A.txt aa.txt Z.txt
$ ls
A.txt Z.txt aa.txt
Files being different only by a numerical string can be sorted on this number at the condition that it is preceded by a separator.
In this case, the following syntax can be used:
ls -x1 file | sort -t'<char>' -n -k2
Example:
ls -1 TRA*log | sort -t'_' -n -k2
TRACE_1.log
TRACE_2.log
TRACE_3.log
TRACE_4.log
TRACE_5.log
TRACE_6.log
TRACE_7.log
TRACE_8.log
TRACE_9.log
TRACE_10.log
From the man page (for bash ls):
Sort entries alphabetically if none of -cftuSUX nor --sort.
Check your .bashrc
file for aliases.
The ls
utility should conform to IEEE Std 1003.1-2001 (POSIX.1
) which states:
22027: it shall sort directory and non-directory operands separately according to the collating sequence in the current locale.
26027: By default, the format is unspecified, but the output shall be sorted alphabetically by symbol name:
- Library or object name, if −A is specified
- Symbol name
- Symbol type
- Value of the symbol
- The size associated with the symbol, if applicable
ls -X works for that purpose, in case you have aliased ls to a more useful default.
In Debian Jessie, this works nice:
ls -lah --group-directories-first
# l=use a long listing format
# a=do not ignore entries starting with .
# h=human readable
# --group-directories-first=(obvious)
# Note: add -r for reverse alpha
# You might consider using lh by appending to ~/.bashrc as the alias:
~$ echo "alias lh='ls -lah --group-directories-first'" >>~/.bashrc
# -- restart your terminal before using lh command --