Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace first occurrence in package.json file

Having hard time replacing only the occurrence of the version property value in my package.json file

what i tried

CURRENT_VERSION=$(node -p "require('./package.json').version")
sed  -i '0,/$CURRENT_VERSION/{s//1.0.2/}' package.json

-- file doesn't change --

my package.json file

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "version": "1.0.0",
  "dependencies": {
    "demo-dep": "1.0.0"
  }
}

>Solution :

Parsing json files with sed is too prone to errors, try to avoid that and use specialized tools for the job.

npm itself can be used to set versions hassle-free, see https://docs.npmjs.com/cli/v8/commands/npm-version

In your case running npm version 1.0.2 should work

If you still want to use sed – something like this should work

sed -i "0,/$CURRENT_VERSION/ s/$CURRENT_VERSION/1.0.2/"

But if npm is not an option – i suggest you to use jq

tmp=$(mktemp); jq '.version = "1.0.2"' package.json > "$tmp" && mv "$tmp" package.json

it will certainly be less error-prone

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading