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

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

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

答案1

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.)

相关内容