Shiboe
Shiboe

Reputation: 787

sed command to replace wildcard string with contents of a file containing javascript

I've worked up to the following:

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

The goal is:

  1. read some lines of js from a file and save that to variable routes (working)
  2. find a wildcarded string return[[{path: * }]] in js file (working)
  3. replace that string with the content of variable $routes (failing)

Right now, I'm getting errors:

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.

Which seems like perl isn't dropping the contents of the variable into the replacement, and is instead trying to interpret the contents as more commands.

The contents of the file is more or less:

return (() => {
  let template = window.CONFIG.template;

  let routeMap = {
    foo: [[{
      path: '',
      loadChildren: 'app/modules/foo/foo.module#fooModule'
    }]]
  }

  return routeMap[template];
})();

The variable contains javascript which requires some level of conflicting syntax. How can I correct this so that a direct replacement is made with the exact content of the variable without conflicts?

Upvotes: 1

Views: 171

Answers (1)

LMC
LMC

Reputation: 12777

Try holding your string in a variable and then replace it with printf in a file by file basis

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

Upvotes: 1

Related Questions