'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"
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 1:[1]
With your shown samples, please try following awk code. Written and tested in GNU awk.
s='import * as module from "/test.js"'
echo "$s" | awk '/^import.*from[[:space:]]+"\//{sub(/\//,"/myFolder&")} 1'
Explanation: Following is the detailed explanation for above code.
- Creating a variable named
swhich has all the values as input forawkprogram in it. - Printing it by
echocommand and passing it as a standard input toawkprogram here. - In
awkprogram checking condition if a line satisfies^import.*from[[:space:]]+"\/regex(which basically checks if line starts from import till from followed by space(s) followed by "/) if this is TRUE then following action will happen. - using
subfunction ofawkto perform substitution to substitute/with/myFolder/as per requirement. - Then mentioning
1is a way to print current line inawk.
Solution 2:[2]
Using sed
$ sed 's|/[^"]*|/myFolder&|' input_file
import * as module from "/myFolder/test.js"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RavinderSingh13 |
| Solution 2 | HatLess |
