skip to Main Content

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


  1. Don’t use sed on JSON data, use a JSON-specific tool:

    jq --arg branch "$BRANCH_NAME" '.settings.branch = $branch' settings.json > tmpfile 
    && mv tmpfile settings.json
    
    Login or Signup to reply.
  2. 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"
     }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search