15

I have a couple files and ls sorts them like this:

a
_b
c

but I want to have

_b
a
c

How can I do that?

2
  • 2
    Might I ask why?
    – RolandiXor
    Jun 8, 2011 at 19:49
  • 4
    I use the underscore to denote special directories that need to go to top. In my projects folder, I have proj_a, proj_b and _old_projects. It is no use if this folder is within the o-projects. Jun 8, 2011 at 21:10

4 Answers 4

10

As a one-off command you can do this:

LC_COLLATE=C ls

Or you can add export LC_COLLATE="C" to your .bashrc to make it permanent (may have unexpected results sorting elsewhere).

More information on Ubuntu forums.

5
  • 1
    I guess I will just alias ls with that, so that it does not have side effects. Jun 8, 2011 at 21:05
  • This doesn't work for me. I get this -> paste.pocoo.org/show/403333 (it's german but it shouldn't matter)
    – dAnjou
    Jun 9, 2011 at 9:55
  • 3
    @dAnjou LC_COLLATE=C ls sets the traditional POSIX sorting order, which is by ASCII in which uppercase comes before underscore. To have underscores sort before uppercase you'd have to get under the bonnet and create a custom locale definition under /usr/share/i18n/locales.
    – misterben
    Jun 9, 2011 at 10:36
  • 2
    This may have worked in the past, but it's not working on Ubuntu 12.04.
    – Mikel
    Jun 1, 2012 at 19:18
  • 1
    As of Ubuntu 14.04, LC_COLLATE=C ls does not work, but LC_ALL=C ls does.
    – jwodder
    Jan 17, 2015 at 3:48
6

Just in case there isn't a built-in way to do this, you could use a simple replacement for sort:

#!/usr/bin/env python

import sys

for i in sorted(sys.stdin):
    sys.stdout.write(i)

Save it, for example, at /bin/pysort and make it executable (sudo cp whatever.py /bin/pysort and sudo chmod a+x /bin/pysort), and run it as ls | pysort:

stefano@lenovo:~/t$ ls | pysort
_b
a
c
1
  • 1
    I would probably put it in ~/bin but nice fallback. It is probably better to use globbing within python since the output of ls might be strange if a filename contains a newline. Jun 8, 2011 at 21:08
1

would ls | sort not do exactly what you need?

3
  • 2
    no, that sorts it as "a _b c" Jun 8, 2011 at 19:55
  • 1
    no! and sort also has not got an option for this :-)
    – Rinzwind
    Jun 8, 2011 at 19:55
  • 3
    It is strange that sort has so many special sorting ways but not the "use ASCII value" one … Jun 8, 2011 at 21:07
1

As of 2024, the LC_COLLATE=C ls option works perfectly for me on Ubuntu 22.04 with sort (GNU coreutils) 8.32 and LANG=en_GB.UTF-8. However, in case this does not work on your platform/locale, you could do this fairly easily with perl:

ls | perl -e '@f=sort <>; print @f'

I was also surprised that I couldn't find a relevant option in the sort man page.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .