awk 或其他命令如何获取字符串卷曲结果的变量值?

Awk or other command how to get variable value on string curl results?

在 bash 脚本中,我 运行 是 POST 请求获取数据的 curl

f_curl_get_data (){

read -p "start date : " start_date
read -p "end date : " end_date

# (!) NOTE 
# - the date time format must be YYYY-MM-DD

mng_type=users
user=myuser
secret=mysecret

curl --location --request POST 'https://myapi.com/api/v2.1/rest/exports' \
    --header 'Content-Type: application/json' \
    --header 'SDK-APP-ID: '$user'' \
    --header 'SDK-SECRET: '$secret'' \
    --data-raw '{
        "type":"'$mng_type'",
        "start_date":"'$start_date'",
        "end_date": "'$end_date'"
    }' 

}

我得到以下结果

{"results":{"created_at":"2020-03-13T07:04:14Z","download_url":"","error_message":"","original_filename":"2020-03-13T07:04:14Z_exported_users.json","percentage":0,"resource_name":"users","size":0,"status":"started","total_rows":0,"unique_id":"37c23e60-5b83-404a-bd1f-6733ef04463b"},"status":200}

如何使用 awk 命令或其他命令从变量 "unique_id" 中获取值?

37c23e60-5b83-404a-bd1f-6733ef04463b

谢谢你

使用 GNU awk 和 json 扩展:

$ gawk '
@load "json"                                # load extension
{
    lines=lines [=10=]                          # in case of multiline json file
    if(json_fromJSON(lines,data)!=0) {      # explode valid json to an array
        print data["results"]["unique_id"]  # print the object value
        lines=""                            # in case there is more json left
    }
}' file

输出:

37c23e60-5b83-404a-bd1f-6733ef04463b

扩展可以在那里找到:

http://gawkextlib.sourceforge.net/json/json.html

...或者您可以使用 jq:

$ jq -r '.results.unique_id' file
37c23e60-5b83-404a-bd1f-6733ef04463b

使用 sed

sed -e 's/.*unique_id":"\(.*\)\"}.*//'

演示:

:>echo '{"results":{"created_at":"2020-03-13T07:04:14Z","download_url":"","error_message":"","original_filename":"2020-03-13T07:04:14Z_exported_users.json","percentage":0,"resource_name":"users","size":0,"status":"started","total_rows":0,"unique_id":"37c23e60-5b83-404a-bd1f-6733ef04463b"},"status":200}' | sed -e 's/.*unique_id":"\(.*\)\"}.*//'
37c23e60-5b83-404a-bd1f-6733ef04463b