sed or awk command to replace a variable with a json object like below

I have an object string in {"name": "VAULT", "value": "jsakjkaj"},{"name": "IMAGE", "value": "busybox"} format in a file called ENV.json.

i am assigning the content of ENV.json to a variable called VAL like below.

VAL=`cat ENV.json`

and i have a placeholder %KEYVALUES% in another file test.json . i want to replace %KEYVALUES% with $VAL like below

sed 's/%KEYVALUES%/'${VAL}'/g' test.json --> but this is throwing the error
sed: -e  expression #1, char 16: unterminated `s' command

Please help.

Upvotes: 1

Views: 1035

Answers (1)

Ed Morton
Ed Morton

Reputation: 204731

$ cat ENV.json
{"name": "VAULT", "value": "jsakjkaj"},{"name": "IMAGE", "value": "busybox"}

$ cat test.json
foo %KEYVALUES% bar

$ val=$(<ENV.json)
$ echo "$val"
{"name": "VAULT", "value": "jsakjkaj"},{"name": "IMAGE", "value": "busybox"}

$ val="$val" awk 'BEGIN{old="%KEYVALUES%"; new=ENVIRON["val"]} s=index($0,old){$0 = substr($0,1,s-1) new substr($0,s+length(old))} 1' test.json
foo {"name": "VAULT", "value": "jsakjkaj"},{"name": "IMAGE", "value": "busybox"} bar

If it were me, though, I wouldn't read ENV.json into a shell variable first, I'd just do it all in awk:

$ awk '
    BEGIN { old="%KEYVALUES%" }
    NR==FNR { new=(NR>1 ? new ORS : "") $0; next }
    s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+length(old)) }
1' ENV.json test.json
foo {"name": "VAULT", "value": "jsakjkaj"},{"name": "IMAGE", "value": "busybox"} bar

Upvotes: 1

Related Questions