You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用AWK命令验证并清理CSV中的DOB字段(仅保留YYYY-MM-DD格式)

使用AWK验证并清理CSV中的出生日期字段

要实现CSV文件中DOB字段的验证与清理——仅保留YYYY-MM-DD格式的有效日期(字段含有效日期+其他文本时仅保留日期,无效数据置空),可以用以下AWK命令:

BEGIN {FS=OFS=","}
NR==1 {print; next}
{
    valid_dob = ""
    # 匹配YYYY-MM-DD格式并提取年、月、日片段
    if (match($2, /.*([0-9]{4})-([0-9]{2})-([0-9]{2}).*/, date_parts)) {
        year = date_parts[1] + 0
        month = date_parts[2] + 0
        day = date_parts[3] + 0

        # 验证年份范围(可根据需求调整,这里设为1900-2100)
        if (year >= 1900 && year <= 2100) {
            # 验证月份合法性
            if (month >= 1 && month <= 12) {
                # 根据月份确定最大天数
                max_day = 31
                if (month ~ /^(4|6|9|11)$/) max_day = 30
                else if (month == 2) {
                    # 处理闰年二月的天数
                    max_day = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ? 29 : 28
                }
                # 验证天数合法性
                if (day >= 1 && day <= max_day) {
                    valid_dob = date_parts[1] "-" date_parts[2] "-" date_parts[3]
                }
            }
        }
    }
    $2 = valid_dob
    print
}

命令逻辑拆解:

  • BEGIN块:设置输入输出分隔符为逗号,适配CSV格式。
  • 表头处理:第一行直接打印,跳过验证逻辑。
  • 日期匹配与提取:用match函数配合正则捕获组,从第二列中提取可能的日期片段(兼容前后带其他文本的情况)。
  • 多层有效性验证:
    1. 校验年份范围,排除12056这类不合理年份;
    2. 确保月份在1-12之间;
    3. 根据月份和闰年规则验证天数(比如四月最多30天,闰年二月29天)。
  • 字段替换与输出:验证通过则保留有效日期,否则置空,最后打印整行。

测试效果:

输入源数据:

name,dob
pater,2022-12-10
john,1900-10-23
cader,apr 10 12056
tina,2020-maple road
mike,2019-01-35
carl,2010-03-18 new york
anne,hi how are you?

执行命令后输出:

name,dob
pater,2022-12-10
john,1900-10-23
cader,
tina,
mike,
carl,2010-03-18
anne,

完全符合预期需求。

内容的提问来源于stack exchange,提问作者Gammix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 04:00:56