bash sort - how do I sort using timestamp

后端 未结 2 667
南方客
南方客 2020-12-21 13:39

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

2条回答
  •  隐瞒了意图╮
    2020-12-21 14:12

    sort is a nice tool but it doesn't have enough bells and whistles to take pseudo-xml apart, convert an attribute to a sensible time value, and then sort on it.

    However, such tools do exist. While the best way to do this would probably be with an XSLT transform, if the file is really as consistent as your example command expects, you could extract the time values with cut -d'"' -f4, and you can convert each one to a more sensible format with date. For example (needs GNU date):

    paste <(cut -d'"' -f4 file.txt | date -f- +%s) file.txt | sort -n | cut -f2-
    

    which extracts the date-times, one per line; feeds them to date to convert them to seconds-since-epoch; pastes each timestamp on the beginning of each line; sorts the pasted result numerically, now with numeric timestamps at the beginning, and finally removes the timestamp to get the original file back.

    Test:

    $ cat >file.txt <<'EOF'
    
    
    
    
    
    
    EOF
    $ paste <(cut -d'"' -f4 file.txt | date -f- +%s) file.txt | sort -n | cut -f2-
    
    
    
    
    
    
    

提交回复
热议问题