I’m attempting to use the linux command sed
to dynamically replace the value of the "branch" property. But, here is the kicker.. I’m using a bash environment variable as the value.
The environment variable:
export BRANCH_NAME=release/feature-branch
Here is my json:
{
"settings": {
"repo": "myrepo/my-service",
"branch": "feature/addition-1"
}
}
How do I use sed to transform the JSON into:
{
"settings": {
"repo": "myrepo/my-service",
"branch": "release/feature-branch"
}
}
What I’ve Tried so far
I have tried this other example from stackoverflow with several variations, but was unsuccessful with this:
sed -i '/branch/c "branch" : "${BRANCH_NAME}"' settings.json
The result was:
{
"settings": {
"repo": "myrepo/my-service",
"branch": "${BRANCH_NAME}"
}
}
2
Answers
Don’t use sed on JSON data, use a JSON-specific tool:
Your best option is to use something that knows how to read and write JSON syntax. The canonical tool is
jq
. Assuming that we have set the shell variable$BRANCH_NAME
, we do something like this:The problem with this
sed
command:is that single quotes (
'
) inhibit variable expansion. You could do this instead:Notice the somewhat complex quoting going on there; we have effectively:
More specifically:
'/branch/c "branch" : "'
"${BRANCH_NAME}"
'"'
This way, the expression
"${BRANCH_NAME}"
is outside of the single quotes and is expanded by the shell.Demo: