skip to Main Content

I have a list of folders

$ ls -1 . 
_dns
linux
mariadb
minio
mongodb
nginx
_postgresdb
_python
_rabbitmq
redis
sphinx
supervisor
$

I would like to have them in the lexicographic order (the order provide by e.g. the vim sort):

$
_dns
_postgresdb
_python
_rabbitmq
linux
mariadb
minio
mongodb
nginx
redis
sphinx
supervisor
$

I don’t succeed to do that with the unix sort:

$ ls -1 . | sort
_dns
linux
mariadb
minio
mongodb
nginx
_postgresdb
_python
_rabbitmq
redis
sphinx
supervisor
$

even with options:

$ ls -1 . | sort  -g
_dns
linux
mariadb
minio
mongodb
nginx
_postgresdb
_python
_rabbitmq
redis
sphinx
supervisor
$

$ ls -1 . | sort  -b
_dns
linux
mariadb
minio
mongodb
nginx
_postgresdb
_python
_rabbitmq
redis
sphinx
supervisor
$

$ ls -1 . | sort  -n
_dns
linux
mariadb
minio
mongodb
nginx
_postgresdb
_python
_rabbitmq
redis
sphinx
supervisor
$

Note: this question as been answered in a much better way in Unix sort treatment of underscore character

2

Answers


  1. As this post suggests, the issue is in the locale settings.

    Use POSIX C locale to get the result you expect.

    $ cat tmp/filelist.txt  | LC_COLLATE=C /usr/bin/sort
    _dns
    _postgresdb
    _python
    _rabbitmq
    linux
    mariadb
    minio
    mongodb
    nginx
    redis
    sphinx
    supervisor
    

    While with en_US.utf8 locale you would get what you are getting now.

    $ cat tmp/filelist.txt  | LC_COLLATE=en_US.utf8 /usr/bin/sort 
    _dns
    linux
    mariadb
    minio
    mongodb
    nginx
    _postgresdb
    _python
    _rabbitmq
    redis
    sphinx
    supervisor
    

    Note that this answer is based on sort from GNU coreutils version 8.32.

    Login or Signup to reply.
  2. If you want a persistent solution you can export LC_COLLATE

    $ ls -1  | sort
    
    _dns
    linux
    mariadb
    minio
    mongodb
    nginx
    _postgresdb
    _python
    _rabbitmq
    redis
    sphinx
    supervisor
    
    $ export LC_COLLATE=C
    $ ls -1  | sort
    
    _dns
    _postgresdb
    _python
    _rabbitmq
    linux
    mariadb
    minio
    mongodb
    nginx
    redis
    sphinx
    supervisor
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search