'Replace a string using bash file

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?



Solution 1:[1]

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

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mono1
Solution 2