Sorting by Time Units (e.g. ms, s, etc.) in Bash or Shell

3

What would be the easiest way to sort a list of numbers appended with time units in bash or shell? In other words, I'm looking for something similar to "sort -h" but rather than sorting size units, I want to sort time units (ns, us, ms, s).

Here's an example list I wanted to sort:
1.234s
804.2754ms
603.223us
50.1234ms

TLin

Posted 2017-02-12T09:02:40.217

Reputation: 33

good question. to me this looks like 2 bugs in sort -h, or perhaps 1 bug and 1 un-fixable design limitation. 1) us or µs isn't properly handled (bug). 2) s isn't properly handled by itself (possible design limitation). if you convert the s to another unit that works properly (m, k, M), sort -h gets it right. (try it with mg/kg/Mg values!) – quixotic – 2017-02-13T13:31:53.633

Answers

3

Here's one way to solve this problem:

  1. Add a second column, with the times converted to the same unit
  2. Sort the input on the second column
  3. Drop the second column

You could do step 1 with an awk script, this script converts the time units to nanoseconds:

{
    time = $1;
    sub(/[a-z]+$/, "", time);
    unit = $1;
    sub(/^[^a-z]+/, "", unit);

    # convert to nanoseconds
    if (unit == "us") {
        time *= 1000;
    } else if (unit == "ms") {
        time *= 1000000;
    } else if (unit == "s") {
        time *= 1000000000;
    }
    print $1, time
}

If you save this in a file convert.awk, then you can perform steps 1-3 with this pipeline:

awk -f convert.awk input.txt | sort -g -k2 | cut -f1 -d' '

The -g instead of -n is necessary in case some numbers get displayed in exponential notation. (Credit to OP for pointing that out.)

janos

Posted 2017-02-12T09:02:40.217

Reputation: 2 449

Works pretty well. Minor thing: I noticed sometimes the output will be printed in exponential notation, so had to switch to using sort -k2 -g – TLin – 2017-02-13T10:06:56.030

@TLin nice, thanks for pointing that out, added to my answer – janos – 2017-02-13T11:05:04.520

1-n and -g options of sort incompatible, leave only -g – Alex – 2017-02-13T22:02:25.963