解析从 whois 接收到的数据

Parse reveived data from whois to date

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

renewal date: 2021.09.24 12:22:02

接下来我应该怎么做才能使 date 命令生效?

现在我正在 date: invalid date ‘+%s’

#!/bin/bash
target=
# Get the expiration date
expdate=$(whois  | 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))

您需要替换“.”带有“/”以允许它与日期一起使用,因此您可以使用 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 到 return 天:

echo "$expdat"

renewal date:          2021.09.24 12:22:02

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

使用gensub将“.”转换space 作为日期,return 将结果放入变量 dat。暂时做同样的事情,将“:” returning结果替换为tim。使用这些变量使用 mktime 函数获取 fed expdat 变量的纪元格式日期,减去当前纪元日期(从 systime() 获得)并除以 86400 得到天数。

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

替换

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

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