Thursday, April 28, 2022

[SOLVED] I can't use sed or jq with variables including whitespaces

Issue

I want to add a couple fields to a json file in a shell script. The values for both files come in a parameter and there doesn't seem to be a way to make sed or jq work with such values. I've traid with simple and double quotes everywhere but can't make it work.

sh myscript.sh 'value' 'second value'

firstValue=$1
secondValue=$2

jq '.firstField="'$firstValue'" | .secondField="'$secondValue'"' $jsonFileAddress
sed -i '$s/}/,"firstField":"'$firstValue'","secondField":"'$secondValue'"}/' $jsonFileAddress

Solution

Bengamin W. comment put me on track with the use of arguments. I finally managed to append a couple of new fields to an existing json file like this:

echo $(jq --arg a "$firstValue" --arg b "$secondValue" '.firstField=$a | .secondField=$b' $jsonFileAddress) > $jsonFileAddress



Answered By - Rajo
Answer Checked By - Marie Seifert (WPSolving Admin)