How to sort a file, based on its numerical values for a field?
Take a peek at the man page for sort...
-n, --numeric-sort compare according to string numerical value
So here is an example...
sort -n filename
If you are sorting strings that are mixed text & numbers, for example filenames of rolling logs then sorting with sort -n
doesn't work as expected:
$ ls |sort -noutput.log.1output.log.10output.log.11output.log.12output.log.13output.log.14output.log.15output.log.16output.log.17output.log.18output.log.19output.log.2output.log.20output.log.3output.log.4output.log.5output.log.6output.log.7output.log.8output.log.9
In that case option -V
does the trick:
$ ls |sort -Voutput.log.1output.log.2output.log.3output.log.4output.log.5output.log.6output.log.7output.log.8output.log.9output.log.10output.log.11output.log.12output.log.13output.log.14output.log.15output.log.16output.log.17output.log.18output.log.19output.log.20
from man page:
-V, --version-sort natural sort of (version) numbers within text
Well, most other answers here refer to
sort -n
However, I'm not sure this works for negative numbers. Here are the results I get with sort version 6.10 on Fedora 9.
Input file:
-0.907928466796875-0.616149902343751.1354064941406250.48614501953125-0.4140167236328125
Output:
-0.41401672363281250.48614501953125-0.61614990234375-0.9079284667968751.135406494140625
Which is obviously not ordered by numeric value.
Then, I guess that a more precise answer would be to use sort -n
but only if all the values are positive.
P.S.: Using sort -g
returns just the same results for this example
Edit:
Looks like the locale settings affect how the minus sign affects the order (see here). In order to get proper results I just did:
LC_ALL=C sort -n filename.txt