Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I handle forward slash character within a bash script?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 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 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading