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

时间:2018-01-30 20:30:11

标签: bash shell sed

我已做过以下工作:

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

目标是:

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

    现在,我收到了错误:

    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 个答案:

答案 0 :(得分:1)

尝试将字符串保存在变量中,然后逐个文件地将其替换为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