【问题标题】:Parse reveived data from whois to date解析从 whois 收到的数据
【发布时间】:2021-03-31 09:46:23
【问题描述】:

我想制作脚本来显示域到期的剩余天数。 我能够获得域到期日期的行,但我将其 grep 为该格式

renewal date: 2021.09.24 12:22:02

接下来我应该怎么做才能使date 命令正常工作?

现在我收到date: invalid date ‘+%s’

#!/bin/bash
target=$1
# Get the expiration date
expdate=$(whois $1 | egrep -i 'Expiration|Expires on|Renewal Date| head -1 ')
echo "whoisdata:"$expdate

# Turn it into seconds (easier to compute with)
expdate=$(date -d"$expdate" +%s)
# Get the current date in seconds
curdate=$(date +%s) 
# Print the difference in days
echo $(((expdate-curdate)/86400))

【问题讨论】:

  • whoisdata:之后打印什么值?
  • 续订日期:2021.09.24 12:22:02

标签: linux bash date parsing whois


【解决方案1】:

如果你的起始字符串是renewal date: 2021.09.24 12:22:02,那么你可以用AWK解析它:

替换

expdate=$(whois $1 | egrep -i 'Expiration|Expires on|Renewal Date| head -1 ')

expdate=$(whois $1 | egrep -i 'Expiration|Expires on|Renewal Date' | awk -F' ' '{split($3,dte,/\./);split($4,hour,/:/);print dte[1]"-"dte[2]"-"dte[3]" "hour[1]":"hour[2]":"hour[3];}')

【讨论】:

  • #!/bin/bash target=$1 # Get the expiration date #expdate=$(whois $1 | grep -iE 'expir.*date|expir.*on|renew.*date' | head -1 | grep -oE '[^ ]+$') expdate=$(whois $1 | egrep -i 'Expiration|Expires on|Renewal Date' | awk -F' ' '{split($3,dte,/\./);split($4,hour,/:/);print dte[2]dte[3]hour[1]hour[2]dte[1]"."hour[3];}') curdate=$(date +%s) echo $(((expdate-curdate)/86400)) 现在看起来像这样,我得到./domaincheck.sh: line 10: 092412222021: value too great for base (error token is "092412222021")
  • @Krystian 我已经更正了日期格式。
  • 太棒了,谢谢先生
【解决方案2】:

您需要替换“。”使用“/”允许它与日期一起使用,因此您可以使用 sed:

expdat=$(date -d "$(sed -n 's/renewal date:[[:space:]]+//s/\./\//gp' <<< '2021.09.24 12:22:02')" '+%s')

expdat=$(date -d "$(sed -n 's/renewal date:[[:space:]]+//;s/\./\//gp' <<< "$expdat")" '+%s')

使用带有内置日期函数的 GNU awk 来返回日期:

echo "$expdat"

renewal date:          2021.09.24 12:22:02

awk '{ dat=gensub("\\."," ","g",$3);tim=gensub(":"," ","g",$4);print (mktime(dat" "tim)-systime())/86400" days" }' <<< "$expdat"

使用 gensub 转换“.”到日期的空格,将结果返回到变量 dat。对时间做同样的事情,替换“:”将结果返回到 tim。使用这些变量通过 mktime 函数获取 fed expdat 变量的纪元格式日期,减去当前纪元日期(从 systime() 获得)并除以 86400 得到天数。

【讨论】:

  • 我收到date: invalid date ‘renewal date: 2021/09/24 12:22:02’ date: invalid date ‘+%s’
  • 删除renewal date:
  • 我已修改答案以删除续订日期文本
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多