尝试使用 "sort" 对括号中日期的文本文件进行排序

Trying to sort a text file with dates in brackets with "sort"

我正在尝试按日期对文本进行排序。 我的文件格式是:

...
[15/08/2019 - 01:58:49] some text here
[15/08/2019 - 02:21:23] more text here
[15/08/2019 - 02:56:11] blah blah blah
...

我用 sort 命令尝试了多种不同的方法。

一次尝试:“sort -b --key=1n --debug Final_out.txt

sort: using ‘en_US.UTF-8’ sorting rules
sort: key 1 is numeric and spans multiple fields
sort: option '-b' is ignored

^ no match for key
^ no match for key
...
__
.?
^ no match for key
__
.?
^ no match for key
__
sort: write failed: 'standard output': Input/output error
sort: write error

第二次尝试:“sort -n -b --key=10,11 --debug Final_out.txt” 上面产生了相同的输出

快要把我的头发扯下来了。这必须是可能的,它是Linux!有好心人指点一下吗?

正如 Shawnn 所建议的,bash 解决方案如何:

#!/bin/bash

pat='^\[([0-9]{2})/([0-9]{2})/([0-9]{4})[[:blank:]]+-[[:blank:]]+([0-9]{2}:[0-9]{2}:[0-9]{2})\]'
while IFS= read -r line; do
    if [[ $line =~ $pat ]]; then
        m=( "${BASH_REMATCH[@]}" )      # make a copy just to shorten the variable name
        echo -e "${m[3]}${m[2]}${m[1]}_${m[4]}\t$line"
    fi
done < file.txt | sort -t $'\t' -k1,1 | cut -f2-
  • 变量pat是匹配日期时间字段的正则表达式 并将 bash 变量 BASH_REMATCH[@] 分配给日、月、年和时间 按顺序。
  • 提取日期时间字段后,生成新的字符串 由年、月、日和时间按可排序的顺序组成,并在前面加上 当前行的字符串,用制表符分隔
  • 然后整行通过管道传输到 sort 第一个字段的键控。
  • 第一个字段终于 cut 关闭了。

输入文件file.txt:

[10/01/2020 - 01:23:45] lorem ipsum
[15/08/2019 - 02:21:23] more text here
[15/08/2019 - 02:56:11] blah blah blah
[15/08/2019 - 01:58:49] some text here
[14/08/2019 - 12:34:56] dolor sit amet

输出:

[14/08/2019 - 12:34:56] dolor sit amet
[15/08/2019 - 01:58:49] some text here
[15/08/2019 - 02:21:23] more text here
[15/08/2019 - 02:56:11] blah blah blah
[10/01/2020 - 01:23:45] lorem ipsum

这是一种替代但更短的排序方式,使用 gnu awk:

cat file
[10/01/2020 - 01:23:45] lorem ipsum
[15/08/2019 - 02:21:23] more text here
[15/08/2019 - 02:56:11] blah blah blah
[15/08/2019 - 01:58:49] some text here
[14/08/2019 - 12:34:56] dolor sit amet

使用这个 awk:

awk -v FPAT='[0-9:]+' '{ map[,,,] = [=11=] } 
END { PROCINFO["sorted_in"]="@ind_str_asc"; for (k in map) print map[k] }' file
[14/08/2019 - 12:34:56] dolor sit amet
[15/08/2019 - 01:58:49] some text here
[15/08/2019 - 02:21:23] more text here
[15/08/2019 - 02:56:11] blah blah blah
[10/01/2020 - 01:23:45] lorem ipsum