按12小时排序?

时间:2013-08-02 14:46:16

标签: bash sorting time

今天早上快速(可能是愚蠢的)问题:

我的数据被输入到我的脚本中,如下所示:

03:00P - Doctor appointment.
07:00P - Scheduled entry.
10:30A - Another entry.
11:00A - Daytime medication is due.
11:00P - Nighttime medication is due.
11:30P - Staff meeting.

现在我无法更改数据源,输出需要看起来相同,但我需要正确排序。有关解决这个问题的任何想法吗?

谢谢!

3 个答案:

答案 0 :(得分:2)

告诉排序首先对第六个字符进行排序,然后对第一个字符进行排序:

sort -k1.6,1.6 -k1.1,1.5

答案 1 :(得分:0)

如果您从时间开始AP并将其置于时间前面,则只需使用正常的sort命令即可​​正确排序。也许是这样的:

awk '{print substr($1,6), $0}' < input  | sort | cut -d' ' -f2-

awk命令生成如下输出:

P 03:00P - Doctor appointment.
P 07:00P - Scheduled entry.
A 10:30A - Another entry.
A 11:00A - Daytime medication is due.
P 11:00P - Nighttime medication is due.
P 11:30P - Staff meeting.

然后我们sort,然后删除前缀。

答案 2 :(得分:0)

这是一个基于简单Perl脚本的解决方案,该脚本源自Convert 12-hour date/time to 24-hour date/time的答案。

来源s12.pl

#!/usr/bin/env perl
use strict;
use warnings;

sub time_12h_to_24h
{
    my($t12) = @_;
    my($hh,$mm,$ampm) = $t12 =~ m/^(\d\d?):(\d\d?)\s*([AP]M?)/i;
    $hh = ($hh % 12) + (($ampm =~ m/AM?/i) ? 0 : 12);
    return sprintf("%.2d:%.2d", $hh, $mm);
}

while (<>)
{
    my($time_12h, $entry) = split / - /;
    my $time_24h = time_12h_to_24h($time_12h);
    print "$time_24h $time_12h - $entry";
}

请注意,代码同时接受{AMPM}和{AP},并且在AM的大写和小写之间是中性的/ PM指示符,并忽略时间和AM / PM指示符之间的空格。

输入数据

此数据集包含12:05A和12:05P的行以及问题中的数据。

03:00P - Doctor appointment.
07:00P - Scheduled entry.
10:30A - Another entry.
11:00A - Daytime medication is due.
11:00P - Nighttime medication is due.
11:30P - Staff meeting.
12:05A - Just past midnight and long before 11:00A.
12:05P - Just past midday and long before 11:00P.

双重过滤输出

$ perl s12.pl data | sort | sed 's/^..:.. //'
12:05A - Just past midnight and long before 11:00A.
10:30A - Another entry.
11:00A - Daytime medication is due.
12:05P - Just past midday and long before 11:00P.
03:00P - Doctor appointment.
07:00P - Scheduled entry.
11:00P - Nighttime medication is due.
11:30P - Staff meeting.
$

未过滤的输出

$ perl s12.pl data | sort
00:05 12:05A - Just past midnight and long before 11:00A.
10:30 10:30A - Another entry.
11:00 11:00A - Daytime medication is due.
12:05 12:05P - Just past midday and long before 11:00P.
15:00 03:00P - Doctor appointment.
19:00 07:00P - Scheduled entry.
23:00 11:00P - Nighttime medication is due.
23:30 11:30P - Staff meeting.
$

请注意,通过将键列(24小时时间列)放在输出中,sort命令会被简化(通常,它也会加快排序速度)。