26

I have file1:

"$lvl=57"
"$lvl=20"
"$lvl=48"
"$lvl=17"
"$lvl=58"

File2 I want:

"$lvl=17"
"$lvl=20"
"$lvl=48"
"$lvl=57"
"$lvl=58"

Basically numerically sort of file1.

1
  • 2
    When I run a plain Unix sort on your File1, with no options, I get your File2. What are you doing differently?  What are you leaving out of this question? Sep 28, 2017 at 4:49

4 Answers 4

42

I like the -V / --version-sort option found in a few implementations of sort (from GNU sort): it behaves very well for many situations mixing strings and numbers

sort -V

I use this option very often...

In the same direction, with some implementations of ls, ls -v for version-sort ls (from GNU ls).

0
15

You need to tell sort -n to sort on the part after the =:

sort -t = -k 2n
1
  • 3
    @KasiyA -k defines a sort key. See the man page for details. -k2n defines a sort key starting at the second field and ending at the end of the line and makes it a numeric sort key. Nov 21, 2014 at 10:45
1

I found that, you just run sort -h, it will work. They call it --human-numberic-sort.

sort -h file1 > file2
0
0

use sort:

sort -n file1 > file2

-n, --numeric-sort
compare according to string numerical value

 sort -g file1 > file 2

-g, --general-numeric-sort

6
  • 3
    No, all those lines have the same ranking with sort -n since they don't start with a number. The reason it sorts them is the last-resort full-line sort (lexically, not numerically) done for lines with the same ranking. That would sort "$lvl=17" before "$lvl=2". Nov 21, 2014 at 10:02
  • @StéphaneChazelas thanks for pointing out.
    – Hackaholic
    Nov 21, 2014 at 10:12
  • To paraphrase, -n and -g are redundant here as the input is not numerical. So this answer is misleading, hence the downvote (also note that -g and the long options are GNU specific). Nov 21, 2014 at 10:15
  • but -g is good general-numeric-sort
    – Hackaholic
    Nov 21, 2014 at 10:16
  • That's still for sorting numerical values, the difference with -n is that it's not limited to decimal integers. That would still sort "$lvl=17" before "$lvl=2" as part of the last-resort sorting. Nov 21, 2014 at 10:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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