jq substr() 相当于格式化一个值

jq substr() equivalent to format a value

希望你这段时间一切安好。

一头雾水,希望大家多多指教。

使用 'jq' 我想更改所有日期,例如。 19731013(字符串)到 1973-10-13

[
    {
        "Mail": "john@example.com",
        "Name": "Smith",
        "Employee_Number": "000555",
        "First_Name": "John",
        "Company": "ACME",
        "Department": null,
        "Employment_Status": "Retiree",
        "Start_Date": "19770516",
        "Function_Start_Date": "19770516",
        "Group_Phone": "",
        "Job_Title": "Operations Manager Warehousing",
        "Sub_Group": "Exempts",
        "Location": "Tibuktu",
        "Organizational_Unit": null,
        "Date_of_Birth": "19560719",
        "Gender": "1"
    },
    {
        "Mail": "mary@example.com",
        "Name": "Smith",
        "Employee_Number": "000777",
        "First_Name": "Mary",
        "Company": "ACME",
        "Department": null,
        "Employment_Status": "Retiree",
        "Start_Date": "19770516",
        "Function_Start_Date": "19770516",
        "Group_Phone": "",
        "Job_Title": "Manager",
        "Sub_Group": "Exempts",
        "Location": "Tibuktu",
        "Organizational_Unit": null,
        "Date_of_Birth": "19560719",
        "Gender": "2"
    }
] 

是否可以像 CSV 中的 awk 一样使用 substr(.Start_Date,1,5)"-"substr(.Start_Date,6,2)"-"substr(.Start_Date,8,3)

也许我在盯着墙而错过了右边的门?

更新:非常感谢你们,这真是太棒了!

jq -r '.[].Start_Date |= "\(.[0:4])-\(.[4:6])-\(.[6:8])" | .[].Function_Start_Date |= "\(.[0:4])-\(.[4:6])-\(.[6:8])" | .[].Date_of_Birth|="\(.[0:4])-\(.[4:6])-\(.[6:8])"' employees.json > test.json

在 JQ 中,我们有 string slice and string interpolation 语法。

$ jq '.[].Start_Date | "\(.[0:4])-\(.[4:6])-\(.[6:8])"' file
"1977-05-16"
"1977-05-16"

jq 中还有一个正则表达式匹配函数,使用 capture 发出命名的捕获组,稍后可以由 - 加入以形成您想要的日期字符串。

jq '.[].Start_Date | capture("(?<x>[0-9]{4})(?<y>[0-9]{2})(?<z>[0-9]{2})") | join("-")'

这是假设,您的 Start_Date 字段至少有 8 个字符长, 验证小于该字符的长度。