代码之家  ›  专栏  ›  技术社区  ›  ltqbx

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

  •  2
  • ltqbx  · 技术社区  · 6 年前

    我有一个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 回复  |  直到 6 年前
        1
  •  2
  •   chepner    6 年前

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

    $ jq --arg cid "foo" --arg cdt "bar" '
        .header.correlationContext.array[0]={
            correlationId: $cid,
            correlationDateTime: {string: $cdt}
         }' tmp.json
    
        2
  •  1
  •   Abhijit Pritam Dutta    6 年前

    给你:-

    #!/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