Linux – Sorts directory contents, including hidden files, by name in the shell

Sorts directory contents, including hidden files, by name in the shell… here is a solution to the problem.

Sorts directory contents, including hidden files, by name in the shell

Is there a good way to sort directory contents, including hidden files, in the shell? Basically I want to be able to complete the ls directory in my GUI filer. In a typical directory, the output looks like this:

.a_hidden_dir

.b_hidden_dir

.c_hidden_dir

a_dir

b_dir

c_dir

.a_hidden_file

.b_hidden_file

.c_hidden_file

a_file

b_file

c_file

Of course ls has the –-group-directories-first option, but this just makes us part of the sort and ignores the preamble. , it does not sort hidden files to the top.

I would like to be able to sort the output of ls, find, or other path lists in this way. Does anyone know of a good way to do this – maybe sort -k KEYDEF?

Now I’m doing something like this (it assumes the directory names have a slash appended to them):

pathsort(){
    input=$(cat)
    (
        awk '/^\.. +\/$/' <<<"$input" | sort
        awk '/^[^.]. +\/$/' <<<"$input" | sort
        awk '/^\.. +[^/]$/' <<<"$input" | sort
        awk '/^[^.]. +[^/]$/' <<<"$input" | sort
    ) | sed 's/\/$//'
}

\ls -Ap | pathsort

The code above does the job, but it’s far from ideal. Please tell me there is a better way….

Solution

Jonathan Leffler in commen A simple and practical solution is proposed in t: set the local environment variable LANG=C. On my system, the default LANG=en_US. UTF-8 causes undesirable path name ordering characteristics. C obviously refers to byte character ordering using the ASCII character set. The result of setting LANG=C is that the “point files” (including directories) are sorted to the top. Note that LC_ALL=C can also be used because LC_ALL is a LANG and other LC_* variables. In summary, if you want a consistent sorting experience, it is highly recommended to set the locale to C to sort commands.

This is the ultimate solution for the desired path name ordering hierarchy (dotfile dirs > normal dirs > dotfile files > normal files).

LC_ALL=C ls -A --group-directories-first

Note: This also includes symbolic links to files and directories

Similarly, sort any other pathname output source:

findtool | LC_ALL=C sort

Related Problems and Solutions