Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Given the file:

$ cat file
1
a
C
B
2
c
3
A
b

By default sort will:

$ sort file
1
2
3
a
A
b
B
c
C

With LC_COLLATE=C so will sort in uppercase letter before lowercase:

$ LC_COLLATE=C sort file
1
2
3
A
B
C
a
b
c

Is it possible to get sort to reverse the case ordering, that is digits, lowercase then uppercase?

share|improve this question

I'm no expert but I have never seen locale that defines collation like this. AFAIK this collation is only in C where it is based on ASCII values. (Normally I would just solve this by a script.)

However, I have never done this but you might want to look at localedef(1) and locale(5) manpages to get understanding of how locales are defined and eventually define your own one.

Also don't forget that if there are any diacritics or special characters, C locale will not treat them as you might want to. For example, it will not put á near a or Ł near L. In such cases, the language's native locale would be probably a better starting point.

share|improve this answer
LC_COLLATE="en_US.UTF-8"; sort file
share|improve this answer
    
This doesn't sort lowercase before uppercase? ideone.com/Gtyg4Z – iiSeymour May 10 '13 at 16:06
    
Hmm, in my case, it did using your example. – unxnut May 10 '13 at 16:59

Setting LC_COLLATE=C is not always sufficient to sort uppercase before lowercase. You may need to set LC_ALL=C.

That will also take into account non-alphanumeric and even non-printable characters, but if you don't want that there are options -d and -i (described in man sort) to will turn that off.

It will probably fail badly with multibyte input though, such as UTF-8 with non-ASCII characters.

To get lowercase (in order) before uppercase (in order), the best way I can think of that doesn't involve breaking out a full-fledged programming language is inverting the case of all the letters before the sort, and inverting them back afterwards.

tr 'a-zA-Z' 'A-Za-z' < file | LC_ALL=C sort | tr 'a-zA-Z' 'A-Za-z'
share|improve this answer
    
The question is how to get lowercase first not uppercase. – iiSeymour Jul 8 at 15:54
    
@iiSeymour I don't know how I missed that; probably because I was dealing with a machine on which LC_COLLATE=C was somehow not sufficient to separate out upper and lower cases, and stumbled on this SE question while searching for a solution. Edited. – Law29 Jul 8 at 17:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.