1

I have in my package.json file this line :

"version": "5.0.0",

And I want to replace 5.0.0 with another dynamic value. I tried like this :

sed -i "s%5.0.0%5.1.1%g" "package.json" 

But is not good, because I don't know previous value that is 5.0.0. Should I write a regex here?

2
  • What happens if the string 5.0.0 appears in a different line, which is not related to version? You need to describe in your regex the pattern which the line to be modified must fulfil. Note also that in your attempt, a string 5X0Y0 would also be replaced by 5.1.1, because the period matches any single character. Commented Mar 9, 2022 at 13:23
  • @user1934428 : I want to replace the content of "version". For example I have the number 100, when I run sed command I want : "version": "100" Commented Mar 9, 2022 at 13:26

2 Answers 2

2

Change 5.6.7 to whatever you want. You can grep or find -exec to change many files at once.

sed -i -E 's/"version": "([0-9]+(\.[0-9]+)+)",/"version": "5.6.7",/' package.json
Sign up to request clarification or add additional context in comments.

Comments

1

You could use a backreference:

sed -i -E 's/(^ *?"version". *)[0-9.]+(.*)/\1 5.1.1 \2/g''

The \1 guarantees that the string "version" formatted the same as the input, and you don't have to retype this.

4 Comments

Is not working, I have in my package.json file : 5.1.1 "5.0.0"
Right, I forgot the rest of the line. Is fixed now. I tested it with echo '"version": 5.0.0'|sed -E 's/(^ *?"version". *)[0-9.]+(.*)/\1 5.1.1 \2/g'
thx. Is possible somehow to specify the line ? For example search "version" in first 5 lines and replace the value
If you have a new problem, please don't ask in a comment, but post a completely new question. Stackoverflow is meant to become a searchable resource for programming problems. Therefore, the idea is to have one problem dealt with in one question, which gets exactly one accepted answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.