我需要在 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
发布评论