排序命令 - 按月不工作?

Fle*_*phy 3 linux shell bash sort

我有一个时间戳数组...

arr[0]="04-Feb-2021-21-05-48"
arr[1]="18-Jan-2021-12-19-48"
arr[2]="25-Jan-2021-00-24-29"
arr[3]="26-Jan-2021-00-28-33"
arr[4]="04-Feb-2021-21-06-49"
arr[5]="18-Jan-2021-12-19-48"
arr[6]="25-Jan-2021-00-24-29"
arr[7]="26-Jan-2021-00-28-33"
Run Code Online (Sandbox Code Playgroud)

我想对这个数组进行排序并使用以下命令将时间戳排序到一个新数组中..

IFS=$'\n' sorted=($(sort -r -t- -k2.1,2.3M <<<"${arr[*]}")); unset IFS
printf "[%s]\n" "${sorted[@]}"
Run Code Online (Sandbox Code Playgroud)

我得到了这个输出,但这不是我想要的......

[26-Jan-2021-00-28-33]
[26-Jan-2021-00-28-33]
[25-Jan-2021-00-24-29]
[25-Jan-2021-00-24-29]
[18-Jan-2021-12-19-48]
[18-Jan-2021-12-19-48]
[04-Feb-2021-21-06-49]
[04-Feb-2021-21-05-48]
Run Code Online (Sandbox Code Playgroud)

相反,我希望时间戳按降序排序。
那么我如何得到这个结果呢?

[04-Feb-2021-21-06-49]
[04-Feb-2021-21-05-48]
[26-Jan-2021-00-28-33]
[26-Jan-2021-00-28-33]
[25-Jan-2021-00-24-29]
[25-Jan-2021-00-24-29]
[18-Jan-2021-12-19-48]
[18-Jan-2021-12-19-48]
Run Code Online (Sandbox Code Playgroud)

我尝试了这些版本的 sort 命令,没有一个对我有用......

IFS=$'\n' sorted=($(sort -r -t- -k3.1,3.4 -k2.1,2.3M <<<"${arr[*]}")); unset IFS
IFS=$'\n' sorted=($(sort -r -t- -k2.1,2.3M <<<"${arr[*]}")); unset IFS
IFS=$'\n' sorted=($(sort -t- -k2.1,2.3M <<<"${arr[*]}")); unset IFS
Run Code Online (Sandbox Code Playgroud)

更新

我更新了我的问题以澄清我想按降序对时间戳进行排序,而不仅仅是按月份字段对时间戳数组进行排序。

干杯。

cho*_*oba 8

要应用只能在给定的列“反向”,指定它之后-k

sort -t- -k2.1,2.3Mr
#                  ~
Run Code Online (Sandbox Code Playgroud)

  • @FlexMcMurphy,带有`--debug` 的GNU 排序表示“排序:选项'-r' 仅适用于最后的比较”,因此您可能需要明确提及每个关键字段的反转。虽然你确定你需要给出字符位置并且`sort -k3,3r -k2,2Mr -k1,1r -k4` 不这样做吗?(最后一个故意没有结束位置。) (3认同)

sch*_*ity 7

-r在您想要反转的键中使用反转,但试试这个以获得您想要的输出。与其玩复杂的sort's ,让我们通过将字符串转换为适当的日期格式来使它复杂化,然后排序,然后返回到原始格式:

printf "%s\n" "${sorted[@]}" | \
  awk -F'-' '{ print $1" " tolower($2)" "$3" "$4":"$5":"$6 }' | \ # 04 feb 2021 21:05:48
  xargs -I {} date -d {} +"%Y-%m-%d %H:%M:%S" | \ # 2021-02-04 21:05:48
  sort -k1r | \
  xargs -I {} date -d {} +"[%d-%b-%Y-%H-%M-%S]"
Run Code Online (Sandbox Code Playgroud)

输出:

[04-Feb-2021-21-06-49]
[04-Feb-2021-21-05-48]
[26-Jan-2021-00-28-33]
[26-Jan-2021-00-28-33]
[25-Jan-2021-00-24-29]
[25-Jan-2021-00-24-29]
[18-Jan-2021-12-19-48]
[18-Jan-2021-12-19-48]
Run Code Online (Sandbox Code Playgroud)


gle*_*man 5

一些perl:

printf '%s\n' "${arr[@]}" \
| perl -MTime::Piece -lne '
    $t = Time::Piece->strptime($_, "%d-%b-%Y-%H-%M-%S");
    push @dates, [$t, $_];
    END {print for map {$_->[1]} sort {$b->[0] <=> $a->[0]} @dates}
  '
Run Code Online (Sandbox Code Playgroud)