How to sort a file, based on its numerical values for a field?

lukmac picture lukmac · Jan 31, 2011 · Viewed 135.8k times · Source

Example file.txt:

  100 foo
  2 bar
  300 tuu

When using sort -k 1,1 file.txt, the order of lines will not change, though we are expecting :

  2 bar
  100 foo
  300 tuu

How to sort a field consisting of numbers based on the absolute numerical value?

Answer

Andrew White picture Andrew White · Jan 31, 2011

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