使用bash对逗号分隔文件进行排序

时间:2012-11-12 22:54:29

标签: bash sorting

我有以下内容:

    http://www.google.com/site,11/30/2012 6:51:30 PM
    http://www.google.com/site,10/1/2012 6:51:30 PM
    http://www.google.com/site,11/16/2012 6:51:30 PM
    http://www.google.com/site,8/1/2012 6:51:30 PM

我希望它按MM / DD / YYYY

排序
    http://www.google.com/site,8/1/2012 6:51:30 PM
    http://www.google.com/site,10/1/2012 6:51:30 PM
    http://www.google.com/site,11/16/2012 6:51:30 PM
    http://www.google.com/site,11/30/2012 6:51:30 PM

我可以使用sort命令,uniq命令,tr,sed等。我无法访问awk。有任何想法吗 ? sort -t "," -k1有点工作。

3 个答案:

答案 0 :(得分:1)

尝试这样做:

sort -n -t "," -k 2 file.txt

man sort

答案 1 :(得分:1)

while read line; do
    s=$(date -d "${line#*,}" +%s)
    echo $s $line
done < input.txt | sort -n | cut -d ' ' -f2-

因此,对于每一行,从日期字符串(在逗号后面)创建自Epoch以来的秒数,将其用作排序键并将其从结果输出中删除。

答案 2 :(得分:0)

我使用sort命令做了一些工作,发现了我的问题,这似乎有效:

    cat s.txt | sort -n -t"/" -k 4,4n -k 5,5n
    https://www.virustotal.com/,9/16/2012 8:19:00 AM
    https://www.virustotal.com/,10/6/2012 9:20:59 AM
    https://www.virustotal.com/,11/1/2012 9:20:22 AM
    https://www.virustotal.com/,11/4/2012 9:11:02 AM
    https://www.virustotal.com/,11/6/2012 8:50:27 AM
    https://www.virustotal.com/,11/12/2012 6:51:32 PM

反转:

    cat s.txt | sort -n -t"/" -k 4,4nr -k 5,5nr
    https://www.virustotal.com/,11/12/2012 6:51:32 PM
    https://www.virustotal.com/,11/6/2012 8:50:27 AM
    https://www.virustotal.com/,11/4/2012 9:11:02 AM
    https://www.virustotal.com/,11/1/2012 9:20:22 AM
    https://www.virustotal.com/,10/6/2012 9:20:59 AM
    https://www.virustotal.com/,9/16/2012 8:19:00 AM

但是,我需要在逗号后执行此操作,因为具有更多“/”的网站将无法像http://site.com/go/to/somelink,9/16/2012 8:19:00 AM

那样工作