如何检测YAML文件中是否存在早于指定天数的到期日期
检测YAML中Suspended状态的过期截止日期
问题背景
现有file.yaml文件内容如下:
- status: Active duedate: '2023-09-10' notes: "there's nothing important here" - status: Suspended duedate: '2023-05-18' notes: "some important notes go here" - status: Suspended duedate: '2023-09-04' notes: "some other important notes go here" - status: Active duedate: '2023-10-10' notes: "there's nothing here" -
需要实现逻辑:找出所有status: Suspended对应的duedate,如果该日期早于当前日期(至少比今天早1天),则输出指定格式的提示,期望结果如下:
Hear Ye! We have an old duedate here! It is 2023-05-18. Hear Ye! We have an old duedate here! It is 2023-09-04.
核心难点是直接用gt/ge这类符号无法完成日期比较,必须将日期转换为可量化的时间戳再进行判断。
解决方案
方法1:结合awk与date命令处理
先获取今日0点的时间戳,再用awk遍历YAML文件,筛选出Suspended状态的条目,提取截止日期后转换为时间戳,最后完成比较输出:
#!/bin/bash # 获取今日0点的时间戳(秒为单位) today=$(date -d "today 00:00:00" +%s) # 遍历处理YAML文件 awk -v today="$today" ' $1 == "status:" && $2 == "Suspended" { flag=1; next } flag && $1 == "duedate:" { duedate = substr($2, 2, 10) # 去除日期前后的单引号 # 调用date命令转换为时间戳 cmd = "date -d \"" duedate " 00:00:00\" +%s" cmd | getline duedate_ts close(cmd) # 时间戳比较:截止日期早于今日则输出提示 if (duedate_ts < today) { print "Hear Ye! We have an old duedate here! It is " duedate "." } flag=0 } ' file.yaml
方法2:纯awk处理(需GNU Awk 4.1及以上版本)
如果使用GNU Awk 4.1+,可以直接用内置的mktime函数转换日期,无需调用外部date命令:
awk ' BEGIN { # 生成今日0点的时间戳 today_str = strftime("%Y %m %d") today_ts = mktime(today_str " 00 00 00") } $1 == "status:" && $2 == "Suspended" { flag=1; next } flag && $1 == "duedate:" { duedate = substr($2, 2, 10) # 将YYYY-MM-DD格式转为YYYY MM DD,适配mktime要求 gsub("-", " ", duedate) duedate_ts = mktime(duedate " 00 00 00") if (duedate_ts < today_ts) { print "Hear Ye! We have an old duedate here! It is " substr($2, 2, 10) "." } flag=0 } ' file.yaml
两种方法均可准确筛选出符合条件的过期日期,并输出期望结果。
内容的提问来源于stack exchange,提问作者Saeed
相关产品推荐
相关产品推荐

