gpt4 book ai didi

bash - 尝试对括号内日期为 "sort"的文本文件进行排序

转载 作者:行者123 更新时间:2023-12-02 02:33:29 32 4
gpt4 key购买 nike

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

...
[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 -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
  • 最后,第一个字段被切断

输入文件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

关于bash - 尝试对括号内日期为 "sort"的文本文件进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64689995/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com