[英]Recursive multiline find/replace from command line
I am trying to do a find and replace for import statements in js files. 我正在尝试查找并替换js文件中的import语句。 There are a few different variants that I need to be able to account for:
我需要考虑几种不同的变体:
// default-import.js
import foo from 'bar-shared';
// named-import.js
import {Foo} from 'bar-shared/foo';
// type-import.js
import type {FooType} from 'bar-shared/foo';
// multiline-import.js
import {
Foo,
reduceFoo,
} from 'bar-shared/foo';
// multiline-with-type-import.js
import {
Foo,
reduceFoo,
type FooType,
} from 'bar-shared/foo';
// multiple-import.js
import foo from 'bar-shared';
import {Foo} from 'bar-shared/foo';
import {
Baz
reduceBaz
} from 'bar-shared/baz';
My end goal is to replace bar-shared
with @bar/core
. 我的最终目标是用
@bar/core
替换bar-shared
。 But the limitations are: - I don't know what the specific imports are - An import statement can be over multiple lines - There can be multiple import statements for bar-shared
in a single file 但局限性是:-我不知道特定的导入内容-导入语句可以跨越多行-单个文件中可以有多个导入
bar-shared
用于bar-shared
I have gotten reasonably close on with the following: 我在以下方面已经相当接近:
find . -type f -name "*.js" -exec \
perl -0777 -p -i -e "s/^import ([\s\S]*?) from 'bar-shared(.*)'/import \1 from '\@bar\/core\2'/gms" {} +
That script doesn't seem to be finding all of the instances though. 该脚本似乎并没有找到所有实例。 Specifically the final example type, with more than one import statement in the file, seems to be the real problem.
具体来说,最终的示例类型似乎是真正的问题,该类型在文件中具有多个import语句。
It seems that you always need to match from import
to the first from 'bar-shared'
. 似乎您总是需要从
import
匹配from 'bar-shared'
的第一个匹配。 Then 然后
perl -i -0777 -wpe's{import.*?from\s+\x27\Kbar\-shared}{\@bar/core}gs'
The \\x27
is the hexadecimal escape for the single quote (27). \\x27
是单引号( 16 )的十六进制转义 。 The /s
modifier makes .
/s
修饰符使.
match newlines, too, which is all you need to process this multiline string in this way. 也匹配换行符,这就是您以这种方式处理此多行字符串所需要的全部。 The
\\K
discards all previous matches so they need not be captured and replaced. \\K
丢弃所有先前的匹配,因此无需捕获和替换它们。
Tested on your example but I am not sure what may appear inside import
blocks in JS. 在您的示例上进行了测试,但是我不确定JS的
import
块中可能会出现什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.