首页 > 解决方案 > 用VI编辑器中的特定匹配替换每一个匹配的正则表达式?

问题描述

假设我有一个如下的文本文件。

create table "kevin".tb1 {
col1,
col2
}
create table "jhone".tb2 {
col1,
col2
}
create table "jake".tb3 {
col1,
col2

}

我需要通过将出现的每个表所有者名称替换为名为“informix”的相同名称来获取该文本文件,如下所示。

输出应该像

create table "informix".tb1 {
col1,
col2
}
create table "informix".tb2 {
col1,
col2
}
create table "informix".tb3 {
col1,
col2
}

在 vi 编辑器中,

:%s/"kevin"/"informix"/g

我可以单独更换它们,但我需要一次全部更换。

标签: regexlinuxvimviregular-language

解决方案


%s/\(create table\) "\i\+"/\1 "informix"/

解释:

% — run through every line in the file
s/ — search and replace
\(create table\) — match the text and store it in the backreference 1
"\i\+" — match any number (more than 1) of identifier characters inside double quotes
\1 "informix" — replace what is found with backreference 1 (text "create table"), a space and text "informix"

推荐阅读