Home > Enterprise >  Replace value in json files with variable values in shell script
Replace value in json files with variable values in shell script

Time:08-13

I am creating multiple files from a json template file and I need to replace two values in json file by different values which I am storing in variable. Below is how source json look like

Source :

{"parameters": [
            {
                "name": "dir_parm",
                "value": "changethis"
            }
        ],
        "targets": [
            {
                "identifier": "hsotchangethis"
            }
        ]

}

Output what I require:

"parameters": [
            {
                "name": "dir_parm",
                "value": "/apps"
            }
        ],
        "targets": [
            {
                "identifier": "iass02"
            }
      ]
   }

In this way json file has to be updated for directory and host name around 40-50 times.

Below is the sed command I tried but it is getting replaced. File name, hostname , directory all are variables\dynamic.

sed -i '/identifier/c\ \"identifier\" : '${bdhostnm}'/g' $fname

Note- I read we can use jq but in the organization it is not allowed. Any suggestion would be helpful

CodePudding user response:

As asked by user a sed solution: value='/apps' bdhostnm='iass02'

sed '/^[ ]*"identifier":/{s/\("identifier": \)\(.*\)/\1'$bdhostnm'/g};/^[ ]*"value":/{s/\("value": \)\(.*\)/\1'${value/\//\\\/}'/g}'$fname

CodePudding user response:

Since OP doesn't have jq and can't install jq so coming up with this awk solution. Which is written and tested in GNU awk. Here I have created 2 awk variables named valValue and valIdentifier where NEW values for respective(json) fields should be mentioned in them.

Here is the Online demo for used regex in following awk code.

awk -v valValue="/apps" -v valIdentifier="iass02" -v RS="" '
match($0,/^({"parameters": \[\n[[:space:]] \
{\n[[:space:]] "name": "dir_parm",\
\n[[:space:]] "value": ")\
[^"]*("\n[[:space:]] }\n\
[[:space:]] \],\n[[:space:]] \
"targets": \[\n[[:space:]] \
{\n[[:space:]] "identifier": ")\
[^"]*("\n[[:space:]] }\n[[:space:]] \
\]\n [[:space:]] })/,arr){
     print arr[1] valValue arr[2] valIdentifier arr[3]
}
'  Input_file

NOTE: In case someone wants a jq code for this one(though its clearly not a ask in question here), then try like: jq '.parameters[].value |= "/apps" | .targets[].identifier |= "iass02"' Input_file.

  • Related