开发者

Parsing string for retrieving date in bash

开发者 https://www.devze.com 2023-04-06 22:22 出处:网络
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?

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

精彩评论

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