简体   繁体   中英

Edit a js file through shell script

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/" 

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:

  1. 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 "\\"") } '
  2. 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.

sed -i 's#dev : .*#dev : '"'https://api-production.com'",'#' config.js
sed -i 's#content_bucket_name:.*#content_bucket_name:''"live-bucket"','#' config.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM