Search code examples
bashsortingtype-conversion

Convert hh:mm:s to hh:mm:ss


I'm trying to sort a two columns list, where the second column has time as hh:mm:s using sort -k2 e.g.

peer0 23:51:3
peer1 23:51:18
peer2 23:51:15

and I get

peer1 23:51:18

peer0 23:51:3

peer2 23:51:15

Most probably, one issue is the missing 0 before 3 for seconds. Any idea how to add this?

Thank you


Solution

  • Some implementations of sort (e.g. the one from GNU coreutils) offer version sort (-V), which would sort 1:3 before 1:30.

    sort -k2,2V
    

    If your sort does not have this, numerically (-n) sort by the individual time components. If you had only the time, that would be sort -t: -n. But since you have whitespace-separated columns and colon-separated time components, you need a bit of pre- and post-processing to do so.

    If your data does not contain : otherwise, you can use

    < yourFile tr ' ' ':' | sort -t: -n -k2,2 -k3,3 -k4,4 | sed 's/:/ /'