解析字符串以在 bash 中检索日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7516093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing string for retrieving date in bash
提问by maks
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 string to date. How can I do this?
Thanks in advance
我有以下格式的字符串dd/MMM/YYYY:HH:mm:ss(例如13/Jan/2011:08:23:34)我需要将此字符串转换为日期。我怎样才能做到这一点?提前致谢
回答by sorpigal
Try
尝试
GNU Date
GNU 日期
mydate='13/Jan/2011:08:23:34'
date +%s -d "${mydate:3:3} ${mydate%%/*} ${mydate:7:4} ${mydate#*:}"
FreeBSD Date
FreeBSD 日期
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.
基本上,使用 GNU date,您必须将日期重新格式化为 GNU date 可以理解和解析的内容。我选择了一种粗略的方法(在现实世界中它需要更可靠)。FreeBSD 在这方面更好,它允许您指定解析器应该查找的日期格式。
回答by glenn Hymanman
You have to massage the date string to be valid for the datecommand.
您必须修改日期字符串才能对date命令有效。
Given d="13/Jan/2011:08:23:34"
给定的 d="13/Jan/2011:08:23:34"
epoch=$( IFS="/:"; set -- $d; date -d "$1 $2 $3 $4:$5:$6" +%s )d2=${d//\// } # replace slashes with spaces
epoch=$( date -d "${d2/:/ }" +%s )
epoch=$( IFS="/:"; set -- $d; date -d "$1 $2 $3 $4:$5:$6" +%s )d2=${d//\// } # replace slashes with spaces
epoch=$( date -d "${d2/:/ }" +%s )

