【问题标题】:Edit a js file through shell script通过shell脚本编辑一个js文件
【发布时间】:2016-01-21 06:39:15
【问题描述】:

我需要更改 js 文件 config.js 的内容,该文件包含以下值:

dev:'https://api-beta.com'
content_bucket_name: 'content-beta'

我想使用 shell 脚本更改此内容并保存文件。更改后的内容可能如下所示:

dev:'https://api-production.com'
content_bucket_name: 'live-bucket'

我如何通过 shell 脚本做到这一点?

config.js

 unifiedTest.constant('CONFIG', {
    env : 'dev',
    api : {
        dev : 'https://api-beta.com', 
    },
    content_bucket_name :"content-beta",
});

我尝试过的shell脚本

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

【问题讨论】:

  • 你的三个例子不匹配:dev:'api-production.com' is not the same as: dev :'api-beta.com', which is not the same as: dev= spaces matter, the : 或 = 问题,实际上是什么?行尾的 , 也很重要,包装 js 的 '' 也很重要。重写文本文件很容易,但你必须保持一致,并重写现实中的内容。另外,你有 2 美元作为第二个参数,但 sed 有 3 美元,这从哪里来?如果你解决了一致性问题,你的问题就会消失。不需要 \1,只需执行:"s/dev:.*/dev:$2/" 使用相同的语法。

标签: linux bash shell sed sh


【解决方案1】:

您遇到的问题与一个字符串中包含/ 的事实有关,因此您会得到s/\(dev=\).*/\1https://api-production.com/,其中/ 分隔符太多。您有很多选择,但以下是最有意义的两个:

  1. 使用awk(插入换行符以提高可读性):

    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. 为表达式使用不同的分隔符,例如 |(希望 URL 中没有该分隔符;:/、'?'、';'、& 和在一般情况下,# 往往是 URL 替换的错误选择):

    sed -i \
        -e "s|\(content_bucket_name[[:space:]]*:\).*|\1'$1'|" \
        -e "s|\(dev[[:space:]]*:\).*|\1'$3'|"
    

请注意,我将您的替换表达式更改为使用 : 而不是 =,因为这是替换效果 JSON 的要求。

【讨论】:

    【解决方案2】:
    sed -i 's#dev : .*#dev : '"'https://api-production.com'",'#' config.js
    sed -i 's#content_bucket_name:.*#content_bucket_name:''"live-bucket"','#' config.js
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-10
      • 1970-01-01
      • 2014-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      相关资源
      最近更新 更多