代码之家  ›  专栏  ›  技术社区  ›  Shiboe

sed命令将通配符字符串替换为包含javascript的文件的内容

  •  1
  • Shiboe  · 技术社区  · 8 年前

    我已经完成了以下工作:

    routes=`cat "$dir"/file.js`
    perl -pi -w -e 's/return\[\[\{path:.*\}\]\]/'"$routes"'/g;' "$dir"dist/main*bundle.js
    

    目标是:

    1. 从文件中读取几行js并将其保存到可变路由(工作)
    2. 查找通配符字符串 return[[{path: * }]] 在js文件中(工作)
    3. 将该字符串替换为变量$routes的内容(失败)

    现在,我发现了一些错误:

    Unquoted string "window" may clash with future reserved word at -e line 2.
    Unquoted string "template" may clash with future reserved word at -e line 2.
    Unquoted string "path" may clash with future reserved word at -e line 6.
    Regexp modifiers "/d" and "/u" are mutually exclusive at -e line 1, at end of line
    Regexp modifiers "/d" and "/l" are mutually exclusive at -e line 1, at end of line
    syntax error at -e line 1, near "; let routeMap "
    Can't find string terminator "'" anywhere before EOF at -e line 1.
    

    这看起来perl并没有将变量的内容放入替换中,而是试图将内容解释为更多的命令。

    文件内容大致如下:

    return (() => {
      let template = window.CONFIG.template;
    
      let routeMap = {
        foo: [[{
          path: '',
          loadChildren: 'app/modules/foo/foo.module#fooModule'
        }]]
      }
    
      return routeMap[template];
    })();
    

    该变量包含javascript,它需要某种程度的冲突语法。如何更正此问题,以便直接替换变量的确切内容而不发生冲突?

    1 回复  |  直到 8 年前
        1
  •  1
  •   LMC    8 年前

    尝试将字符串保存在变量中,然后逐个文件地用printf替换它

    routes=`cat "$dir"/file.js`
    stack=$(perl -p -w -e 's/return\[\[\{path:.*\}\]\]/%s/g;' "$dir"dist/some_bundle.js)
    printf "$stack" "$route" > "$dir"dist/some_bundle.js
    
    推荐文章