linuxbashsortingcommand

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


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?


Solution

  • 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