1

I have declared a variable: username=user2

the contents of the test json is as follows: { "name": "user1", "city": "Texas" }

I would like to replace the value of name i.e user1 with a variable username I tried the following command: sed -i 's/"name": "user1"/"name": $username/g'

The output was:

{ "name": $username, "city": "Texas" }

Expected Output is:

{ "name": "user2", "city": "Texas" }

How can this be achieved? Thanks in Advance

0

1 Answer 1

2

Do it with jq:

jq -c --arg name "$username"  '.name = $name'

Assuming your input data is exactly as you specified, then the following example works with GNU sed:

sed -E 's/("name"\s*:\s*)"[^"]+"/\1"'"$username"'"/'
1
  • Thanks for the help!! Tried the jq command and it worked for me :) Commented Sep 29, 2023 at 9:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .