Reputation: 899
I have a Json file that has following values
cat file
{
"key1": "value1"
"key2": "value2",
}
I would like to change value1 and value2. Values are dynamic it changes overtime. My sed should work with any value and mylook up should be by key. " my sed command is not helping.
sed -i 's/*\"key2\":*/\"key2\": "someothervalue2"/' file
Upvotes: 1
Views: 1034
Reputation: 47099
You should be using a proper json-parser instead of sed
, e.g. jq
.
infile
{
"key1" : "value1",
"key2" : "value2"
}
You can replace its values like this:
jq '.key1 = "foo" | .key2 = "bar"' < infile
Output:
{
"key1": "foo",
"key2": "bar"
}
Upvotes: 2
Reputation: 133438
Try with awk solution too once.
awk '$1 ~ /key[12]/{match($0,/^ +/);printf substr($0,RSTART,RLENGTH);sub(/value[0-9]+/,"someothervalue2",$3);printf("%s%s",$0,RS);next} 1' Input_file
OR
awk '
$1 ~ /key[12]/{
match($0,/^ +/);
printf substr($0,RSTART,RLENGTH);
sub(/value[0-9]+/,"someothervalue2",$3);
printf("%s%s",$0,RS);
next
}
1
' Input_file
Output will be as follows:
{
"key1" = "someothervalue2"
"key2" = "someothervalue2",
}
If you have more than key1 and key2 into your Input_file then change key[12] to key[0-9]+ and let us know how it goes then.
Upvotes: 1
Reputation: 1
You seem a bit unfamiliar with regex, there are a few problems in your expression. E.g. to match any character you use .
and then add the star (.*
) to match it 0 or more times. You should take some time to get familiar with regex as it will save you time and trouble in the future.
But to achieve the desired outcome i used this command:
sed -i -r 's/("key2" ?= ?).*,?/\1"someothervalue2",/' file
You should put this into a script if you are going to do this a lot so you could just type ./myScript key new_value file
Upvotes: 0