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

Replace js path using unix sed

Good evening everybody.
I’m trying to replace paths at *.js files using unix sed script. So, I wrote correct regex expression and sed does not fall, but I can not get a correct result.

UPD: I’m using macOS

Incoming string: import * as module from "/test"

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

My regex:

 \s\*import(.+)from\s+\['\\"\](\\/.+)[^\n]+

that found a path pattern and returns two groups I needed (* as module and /test.js)

For example I need to change import \* as module from "/test" as import \* as module from "/myFolder/test.js"

So, but my bash command

echo 'import * as module from "/test.js"' |
sed -r "s:\s*import(.+)from\s+['\"](\/.+)[^\n]+:import \1 from \"\/myFolder\2\":g "

returns the original string! Could you help please, what’s wrong with it?

>Solution :

Using gnu-sed:

s='import * as module from "/test.js"'
sed -E "s~\\b(import.+ from )(['\"])([^'\"]+)\2~\1\2/myFolder\3\2~g" <<< "$s"

import * as module from "/myFolder/test.js"

RegEx Explanation:

  • \\b: Match a word boundary
  • (import.+ from ): Match string starting from word import followed by 1+ of any character followed by word from surrounded with space on both sides
  • (['\"]): Match a ' or " as opening quote and capture in group #2
  • ([^'\"]+): Match 1+ of any character that is not a quote and capture in group #3
  • \2: Match same quote as the opening quote

On OSX use this sed:

sed -E "s~(import.+ from )(['\"])([^'\"]+)~\1\2/myFolder\3~g" <<< "$s"
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