生成文件并替换生成的文件中的模板文件中的字符串

时间:2018-04-05 15:07:22

标签: json bash sed jq auto-generate

我有一个JSON文件:

{
    "header": {
        "uuid": "c578592a-a751-4993-9060-53f488597e59",
        "timestamp": 1522938800,
        "productionDateTime": "2018-04-05T14:33:20.000+00:00",
        "producers": {
            "operator": null,
            "application": {
                "com.example": {
                    "id": {
                        "string": "1"
                    },
                    "name": {
                        "string": "Test"
                    }
                }
            },
            "station": null,
            "equipment": null,
            "partner": null,
            "flow": null
        },
        "correlationContext": {
            "array": [{
                "correlationId": "98440498-3104-479e-9c99-f4449ba8f4b6",
                "correlationDateTime": {
                    "string": "2018-04-05T14:30:39.000+00:00"
                }
            }]
        }
    },
}

我想创建n个文件来复制JSON文件,但是使用随机的correlationId和correlationDateTime。

您有任何提示或建议吗?非常感谢提前!

2 个答案:

答案 0 :(得分:2)

使用jq并将适当的随机值生成作为读者的练习:

$ jq --arg cid "foo" --arg cdt "bar" '
    .header.correlationContext.array[0]={
        correlationId: $cid,
        correlationDateTime: {string: $cdt}
     }' tmp.json

答案 1 :(得分:1)

在这里: -

#!/bin/bash
alias uid="python -c 'import sys,uuid; sys.stdout.write(uuid.uuid4().hex)' | pbcopy && pbpaste && echo"
dt=$(date "+%Y%m%d-%H%M%S")
# For above two values I am leaving with you. If you have best option please go for it
i=0
while [ $i -le 20 ]
do
  sed  "/correlationId/s/98440498-3104-479e-9c99-f4449ba8f4b6/"$uid"/;s/2018-04-05T14:30:39.000+00:00/"$dt"/" yourJsonFile.json > testcase$i.json
  i=$((i+1))
done