开发者

Parsing string for retrieving date in bash

I have s string in following format dd/MMM/YYYY:HH:mm:ss(e.g 13/Jan/2011:08:23:34) I need to convert this str开发者_运维百科ing to date. How can I do this? Thanks in advance


Try

GNU Date

mydate='13/Jan/2011:08:23:34'
date +%s -d "${mydate:3:3} ${mydate%%/*} ${mydate:7:4} ${mydate#*:}"

FreeBSD Date

mydate='13/Jan/2011:08:23:34'
date -j -f '%d/%b/%Y:%H:%M:%S' "${mydate}" +%s

Basically, with GNU date you must reformat your date into something GNU date can understand and parse. I chose a crude method (in the real world it would need to be more reliable). FreeBSD is better in this regard and allows you to specify the date format the parser should look for.


You have to massage the date string to be valid for the date command.

Given d="13/Jan/2011:08:23:34"

  1. epoch=$( IFS="/:"; set -- $d; date -d "$1 $2 $3 $4:$5:$6" +%s )
  2. d2=${d//\// } # replace slashes with spaces
    epoch=$( date -d "${d2/:/ }" +%s )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜