Issue
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}"
}
}
Solution
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:
$ jq --arg branch_name "$BRANCH_NAME" \
'.settings.branch = $branch_name' settings.json
{
"settings": {
"repo": "myrepo/my-service",
"branch": "release/feature-branch"
}
}
The problem with this sed
command:
sed -i '/branch/c\ \"branch\" : "${BRANCH_NAME}"' settings.json
is that single quotes ('
) inhibit variable expansion. You could do this instead:
sed -i '/branch/c\ \"branch\" : "'"${BRANCH_NAME}"'"' settings.json
Notice the somewhat complex quoting going on there; we have effectively:
'...something in single quotes'...something outside single quotes...'something inside single quotes...'
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:
$ sed '/branch/c\ \"branch\" : "'"${BRANCH_NAME}"'"' settings.json
{
"settings": {
"repo": "myrepo/my-service",
"branch": "release/feature-branch"
}
}
Answered By - larsks Answer Checked By - Pedro (WPSolving Volunteer)