In a package.json, I’m trying to replace that:
"main": "lib/index.js",
"types": "lib/index.d.ts",
By that :
"main": "./index.js",
"types": "./index.d.ts",
So I wrote a simple script that replaces the string pattern by a dot, like so:
sed 's/lib\//.\//g' package.json
It works when I type it in the terminal.
But when it doesn’t run properly when inserted in a package.json script.
package.json:
"build": "tsc && cp package.json lib/ && cd lib && sed 's/lib\//.\//g' package.json && npm publish ./lib"
Output:
sed: 1: "s/lib//.//g": bad flag in substitute command: '.'
It keeps replacing the escaping backslash by forward slash.
How can I make it work ?
>Solution :
You make changes to a json document and \ has special meaning in json. It’s an escape character there too. You therefore need to escape your escape character:
s/lib\\//.\\//g
or give the json parser the unicode value for backslash:
s/lib\u005c//.\u005c//g
or simpler, don’t use a forward slash as the delimiter in sed when it’s one of the characters that you want to match on:
sed 's,lib/,./,g'
Note that you are not actually modifying the document. To do that, add the sed option -i.
sed -i 's,lib/,./,g' package.json