Reputation: 9303
I have a requirement to change the contents of a js file config.js the file contains values like:
dev:'https://api-beta.com'
content_bucket_name: 'content-beta'
I want to change this content using a shell script and save the file. Changed content can look like:
dev:'https://api-production.com'
content_bucket_name: 'live-bucket'
How can i do this via shell script?
config.js
unifiedTest.constant('CONFIG', {
env : 'dev',
api : {
dev : 'https://api-beta.com',
},
content_bucket_name :"content-beta",
});
shell script i have tried
#!/bin/bash
file=config.js
content_bucket_name=$1
dev=$2
sed -i -e "s/\(content_bucket_name=\).*/\1$1/" \
-e "s/\(dev=\).*/\1$3/"
Upvotes: 1
Views: 4741
Reputation: 1
sed -i 's#dev : .*#dev : '"'https://api-production.com'",'#' config.js
sed -i 's#content_bucket_name:.*#content_bucket_name:''"live-bucket"','#' config.js
Upvotes: 0
Reputation:
The problem you're encountering has to do with the fact that one string has /
in it, so you get s/\(dev=\).*/\1https://api-production.com/
, which has too many /
delimiters. You have a number of choices, but here are the two that make the most sense:
Use awk
(newlines inserted for readability):
awk -v name="$1" -v url="$3" '
/content_bucket_name[[:space:]]*:.*/
{
/* Substitute one occurrence of :.* with :"{name}". */
sub(/:.*/, ":\"" name "\"")
}
/dev[[:space:]]*:.*/
{
/* Substitute one occurrence of :.* with :"{url}". */
sub(/:.*/, ":\"" url "\"")
}
'
Use a different delimiter for the expression, such as |
(hopefully the URL doesn't have that delimiter in it; :
, /
, '?', ';', &
, and #
tend to be bad choices for URL replacements in the general case):
sed -i \
-e "s|\(content_bucket_name[[:space:]]*:\).*|\1'$1'|" \
-e "s|\(dev[[:space:]]*:\).*|\1'$3'|"
Note that I altered your substitutions expression to use :
rather than =
since that's a requirement for the substitution to effect the JSON.
Upvotes: 1