shellsortinggnu-sort

How to sort explicitly positive and negative numbers with GNU sort?


Given a file containing the following numbers:

+1.4
+12.3
-1.0
-4.2

How would one sort it with GNU sort in numerical order?

Using -n or -h doesn't seem to work: the + character is not being treated correctly?

$ echo "+1.4\n+12.3\n-4.2\n-1.0" | sort -h
-4.2
-1.0
+12.3
+1.4

Thanks.


Solution

  • In bash :

    echo -e "+1.4\n+12.3\n-4.2\n-1.0" | sort -g
    

    should do the trick. -e with echo interprets escape sequences. -g with sort compares according to general numerical value.

    Sample Output

    $ echo -e "+1.4\n+12.3\n-4.2\n-1.0" | sort -g
    -4.2
    -1.0
    +1.4
    +12.3
    

    Sidenote: In some shells, echo -e is the default behavior. Check [ this ] ...