I have a package.json file like below:-
{
"name": "app",
"version": "0.0.1",
},
"scripts": {
},
"lint-staged": {
"client/**/*.{js,jsx}": [
"prettier --ignore-unknown --write",
"npm run fix:js:lint"
]
},
"dependencies": {
"@neha/testapp": "0.0.80",
"date-fns": "^2.0.0-alpha.27",,
"react": "^17.0.2",
"react-datepicker": "^2.8.0",
"react-dom": "^17.0.2",
"react-draggable": "^4.4.3",
"react-hot-loader": "^4.13.0",
"react-markdown": "^5.0.2",
"react-redux": "^7.1.3",
"react-router": "^5.1.2",
"react-router-dom": "^5.1.2"
},
}
I want to change the version of @neha/testapp
under dependencies
to something like this by PACKAGE_VERSION
variable
"@neha/testapp": "0.0.80-test"
I tried this so far to reach the nested key but could only reach version
sed -i '/version/s/[^.]*$/'"${PACKAGE_VERSION}\"/" package.json
CodePudding user response:
In GNU awk
with your shown samples please try following code. In case you want to save output into Input_file itself then please run this code first and once you are Happy with results then append > temp && mv temp Input_file
to the end of the code.
awk -v RS= '
match($0,/(},\n[[:space:]] "dependencies": {\n[[:space:]] ")(@neha\/testapp": ")([^"] )/,arr){
print substr($0,1,RSTART-1) arr[1] arr[2] arr[3]"-test" substr($0,RSTART RLENGTH)
}
' Input_file
CodePudding user response:
One sed
idea:
PACKAGE_VERSION='0.0.80-test'
sed -E "s|(@neha/testapp\": \")[^\"]*|\1${PACKAGE_VERSION}|" package.json
Where:
-E
- enable extended regex support (and use of capture groups)(@neha/testapp\": \")
- (1st capture group) look for exact match@neha/testapp": "
[^\"]*
- everything that's not a literal double quote (ie, the version number we want to replace)\1${PACKAGE_VERSION}
- replacement string consists of the contents of the 1st capture group plus the contents of thebash
variablePACKAGE_VERSION
NOTE: if there are multiple entries for @neha/testapp
then this will change all of them
This generates:
{
"name": "app",
"version": "0.0.1",
},
"scripts": {
},
"lint-staged": {
"client/**/*.{js,jsx}": [
"prettier --ignore-unknown --write",
"npm run fix:js:lint"
]
},
"dependencies": {
"@neha/testapp": "0.0.80-test",
"date-fns": "^2.0.0-alpha.27",,
"react": "^17.0.2",
"react-datepicker": "^2.8.0",
"react-dom": "^17.0.2",
"react-draggable": "^4.4.3",
"react-hot-loader": "^4.13.0",
"react-markdown": "^5.0.2",
"react-redux": "^7.1.3",
"react-router": "^5.1.2",
"react-router-dom": "^5.1.2"
},
}
Once OP has verified the results the -i
flag could be added to facilitate an inplace update of the source file.