在 package.json 中使用 sed 的问题
Problem with usage of sed in package.json
在 npm 项目的 package.json 中,我以这种方式使用 sed:
shx sed -i "s/'..\/node_modules\/x\/y\/z\/x.min';/'node_modules\/x\/y\/z\/x.min';/" src/styles/external/application.scss
它只是用正确的替换打印文件的内容。
当我在没有转义的情况下从控制台尝试此操作时,它可以正常工作。
如何进行适当的转义才能使其正常工作?我也尝试过双重转义 - \/
和另一个分隔符 - @.
首先,用双反斜杠转义模式中路径名的所有正斜杠 (/
),即 \/
。如docs中所述,内容如下:
Note: like unix sed
, shx sed
treats /
as a special character, and this must be escaped (as \/
in the shell, or \/
in package.json
) if you intend to use this character in either the regex or replacement string. Do not escape /
characters in the file path.
此外,将提供给 sed s
command 的模式包含在 JSON 转义双引号中,即 \"...\"
package.json
...
"scripts": {
"replace": "shx sed -i \"s/'..\/node_modules\/x\/y\/z\/x.min';/'node_modules\/x\/y\/z\/x.min';/g\" src/styles/external/application.scss"
^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^
},
...
注意给定的 npm 脚本还包括 g
标志。
运行 npm run replace
将替换所有实例:
'../node_modules/x/y/z/x.min';
在 src/styles/external/application.scss
处的文件内容中包含以下内容:
'node_modules/x/y/z/x.min';
在 npm 项目的 package.json 中,我以这种方式使用 sed:
shx sed -i "s/'..\/node_modules\/x\/y\/z\/x.min';/'node_modules\/x\/y\/z\/x.min';/" src/styles/external/application.scss
它只是用正确的替换打印文件的内容。 当我在没有转义的情况下从控制台尝试此操作时,它可以正常工作。 如何进行适当的转义才能使其正常工作?我也尝试过双重转义 - \/ 和另一个分隔符 - @.
首先,用双反斜杠转义模式中路径名的所有正斜杠 (
/
),即\/
。如docs中所述,内容如下:Note: like unix
sed
,shx sed
treats/
as a special character, and this must be escaped (as\/
in the shell, or\/
inpackage.json
) if you intend to use this character in either the regex or replacement string. Do not escape/
characters in the file path.此外,将提供给 sed
s
command 的模式包含在 JSON 转义双引号中,即\"...\"
package.json
...
"scripts": {
"replace": "shx sed -i \"s/'..\/node_modules\/x\/y\/z\/x.min';/'node_modules\/x\/y\/z\/x.min';/g\" src/styles/external/application.scss"
^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^
},
...
注意给定的 npm 脚本还包括 g
标志。
运行 npm run replace
将替换所有实例:
'../node_modules/x/y/z/x.min';
在 src/styles/external/application.scss
处的文件内容中包含以下内容:
'node_modules/x/y/z/x.min';