user1679671
user1679671

Reputation:

bash, change line in json file

everyone.

I have a json file:

{
     "id" : "123",
     "firstname" : "john",
     "lastname" : "doe",
     "tel" : "123"
}

fields can have any values.

Is there a way using sed, awk or anything else to change a line in this file like:

"firstname" : "john" -> "firstname" : "bob"

The value can be any.

Thanks in advance.

Upvotes: 1

Views: 1421

Answers (4)

Claes Wikner
Claes Wikner

Reputation: 1517

It works in nawk and mawk as well.

    awk '{sub(/john/,"bob")}1' file

output
{
     "id" : "123",
     "firstname" : "bob",
     "lastname" : "doe",
     "tel" : "123"
}

Upvotes: 0

James Brown
James Brown

Reputation: 37464

Another in awk. Using sub() and regex to replace the last quoted string on a record with string filename on it:

$ awk '/firstname/{sub(/\"[^\"]*\",?$/,"\"bob\"")}1' file
{
     "id" : "123",
     "firstname" : "bob"
     "lastname" : "doe",
     "tel" : "123"
}

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133780

Though json files should be handled by different editors I believe, since you have tagged awk here so trying to help here.

awk '/"firstname"/{$3="\042bob\042\054"} 1' Input_file

Output will be as follows.

{
     "id" : "123",
"firstname" : "bob",
     "lastname" : "doe",
     "tel" : "123"
}

In case you want to save the output into Input_file itself then you could add above_command > temp_file && mv temp_file Input_file too.

EDIT: Also if you want to keep initial space of that line, you could try following too then.

awk '/"firstname"/{$1="     "$1;$3="\042bob\042\054"} 1'   Input_file

Output will be as follows then.

{
     "id" : "123",
     "firstname" : "bob",
     "lastname" : "doe",
     "tel" : "123"
}

Upvotes: 0

Cyrus
Cyrus

Reputation: 88999

Update value in json file with jq:

jq '."firstname" = "bob"' file

Output:

{
  "id": "123",
  "firstname": "bob",
  "lastname": "doe",
  "tel": "123"
}

Upvotes: 4

Related Questions