bash sort

编程入门 行业动态 更新时间:2024-10-27 16:34:46
本文介绍了bash sort - 如何使用时间戳进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要在 linux 中使用 shell 排序对文件进行排序.排序需要基于每个文件行中包含的时间戳值.时间戳的格式不规则,并且没有指定前导零到月份、日期等,所以我执行的排序不正确(即它们的格式是M/D/YYYY H:MI:S AM";所以所以10/12/2012 12:16:18 PM"出现在7/24/2012 12:16:18 PM"之前,它出现在7/24/2012 12:17:18 AM"之前).

I need to sort a file using shell sort in linux. The sort needs to be based on timestamp values contained within each of file's rows. The timestamps are of irregular format and don’t specify the leading zeros to months, days, etc, so the sorts I am performing are not correct (i.e. their format is "M/D/YYYY H:MI:S AM"; so so "10/12/2012 12:16:18 PM" comes before "7/24/2012 12:16:18 PM", which comes before "7/24/2012 12:17:18 AM").

是否可以根据时间戳排序?

Is it possible to sort based on timestamps?

我正在使用以下命令对文件进行排序:

I am using the following command to sort my file:

sort -t= -k3 file.txt -o file.txt.sorted

(使用等号作为分隔符 => -t=; 使用第三列作为排序列 => -k3)

(use equal sign as a separator => -t=; use 3rd column as a sort column => -k3)

示例文件如下:

<r id="abcd" t="10/12/2012 12:16:17 AM"><d><nv n="name" v="868" /><nv n="name0" v="73" /><nv n="name1" v="13815004" /></d></r> <r id="defg" t="7/24/2012 12:16:17 PM"><d><nv n="name" v="0" /><nv n="name0" v="0" /><nv n="name1" v="0" /></d></r> <r id="abcd" t="7/24/2012 12:16:17 PM"><d><nv n="name" v="0" /><nv n="name0" v="0" /><nv n="name1" v="0" /></d></r> <r id="zxy" t="7/24/2012 12:16:17 PM"><d><nv n="name" v="0" /><nv n="name0" v="0" /><nv n="name1" v="59542676" /></d></r> <r id="fghj" t="7/24/2012 12:16:17 PM"><d><nv n="name" v="38" /><nv n="name0" v="0" /><nv n="name1" v="3004537" /></d></r> <r id="defg" t="7/24/2012 12:16:18 AM"><d><nv n="name" v="177" /><nv n="name0" v="0" /><nv n="name1" v="5888870" /></d></r>

推荐答案

linux date 命令在解析日期方面做得很好,它可以将它们翻译成更可排序的东西,比如简单unix 时间整数.

The linux date command does a fine job of parsing dates like this, and it can translate them into more sortable things, like simple unix-time integers.

例子:

cat file | while read line; do datestring=$(sed -e 's/^.* t="([^"]*)".*$/1/' <<<"$line") echo "$(date -d "$datestring" +%s) $line" done | sort -n

如果您希望再次删除该 unix 时间戳,则可以通过适当的 cut 调用传递它.

then you could pass that through the appropriate cut invocation if you want that unix timestamp removed again.

更多推荐

bash sort

本文发布于:2023-10-28 08:50:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536145.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:bash   sort

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!