4

I need to use sed to modify the 3rd line in my.json file as line shown below.

How do I replace a changing key value( this example shows "group-1") with the variable value that is assigned to $username?

    "name": "group-1",
1
  • 3
    Be very wary attempting to parse json with general shell tools. There is a very specific tool for this job called jq (json query), which handles json and json arrays properly. That said, if "name" only appears once in the file, you can safely use the following expression to substitute $username, sed "/\"name\":/s/\(^[^:]*[:][ ]\).*$/\1\"$username\",/" Commented May 10, 2018 at 5:31

1 Answer 1

7

You can replace like below

Linux

 sed -i 's/\"name\":.*/\"name\": '${username}'/g' "/path/to/my.json"

MacOS

   sed -i "" 's/\"name\":.*/\"name\": '${username}'/g' "/path/to/my.json"
Sign up to request clarification or add additional context in comments.

2 Comments

Based on the example, it should be sed 's/"name":.*/"name" : '${username}'/g' instead. You'll also need to take care of potential extra spaces after the quotes. Goes on to say you shouldn't attempt parsing with the wrong tools.
it doesn't keep the comma at the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.