Home > Software engineering >  Json value replacement with Sed
Json value replacement with Sed

Time:02-21

I have the following package.json file:

{
  "name": "test",
  "version": "1.0.1",
  "license": "TEST-1.1",

...

}

I want to edit the file and replace 1.0.1 value with $RELEASE_VERSION value (ex. RELEASE_VERSION=1.0.2). The word version: appears again in the file multiple times, it has to be replaced only once (only the first time that version: appears).

I've tried sed -i '0,/version/c\\ \\ "version\": \"'$RELEASE_VERSION'\",' package.json but it removes the first lines of the file instead of only changing the version: content. I'm using \\ in order to escape \ character in Jenkins shell.

P.S. I've used jq and it works as expected (jq '.version="'$RELEASE_VERSION'"' package.json) but the problem is that I have to > to a temp file and mv that into the original json file. In git diff this appears as the whole file has changed instead of only the version value, plus it changes line endings so I have to convert back in clrf. That's why I'm asking for a sed work-around.

Thanks in advance!

CodePudding user response:

You can set exact line where you want to make change, for example:

sed -i '3d' package.json                        # this line will find and deletes line (3 in this case)
sed -i '3 i\  "version": "1.0.2",' package.json # this one insert string in file

"3" in second command represents line in where you want to insert string from the rest of the command after \i and on. I'm just not 100% sure about apostrophes, maybe there you would have to do some change, but this should work fine. I used it when i needed for one script to change another one.

CodePudding user response:

Using bash:

jq --arg rv "$RELEASE_VERSION" '.version = $rv' package.json > tmp &&
sed $'s/$/\r/' tmp > package.json &&
rm -f tmp

Using sed to parse json is not a great idea.

  • Related