28

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.

peterh
  • 9,731
yisha
  • 909

4 Answers4

51

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).

JJoao
  • 12,170
  • 1
  • 23
  • 45
17

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

sort -t = -k 2n
  • 4
    @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. – Stéphane Chazelas Nov 21 '14 at 10:45
5

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

sort -h file1 > file2
peterh
  • 9,731
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

Hackaholic
  • 2,051
  • 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". – Stéphane Chazelas Nov 21 '14 at 10:02
  • @StéphaneChazelas thanks for pointing out. – Hackaholic Nov 21 '14 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). – Stéphane Chazelas Nov 21 '14 at 10:15
  • but -g is good general-numeric-sort – Hackaholic Nov 21 '14 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. – Stéphane Chazelas Nov 21 '14 at 10:18
  • @Hackaholic: -g is not a general-purpose numerical sort. It's much slower than the plain -n numeric sort, but -g can handle scientific notation, which is not needed here. See the info page of sort for more details. – PM 2Ring Nov 21 '14 at 10:19