1

如何在 VIM 中实现以下内容

substitute/regex_this_word/regex_with_another_word_from_the_same_line

例如

select "ali" as name where _placeholder = _placeholder
union
select "sam" as name where _placeholder = _placeholder

申请后

:%s/_placeholder/anythin_between_quotation/

变成

select "ali" as name where ali = ali
union
select "sam" as name where sam = sam

例如2

select id, "_placeholder" as vul members_repeater/vul/none

申请后

:%s/_placehold/\=something_like_regexp(getline('.'),'regexp_pattern_to_select_everthing_after_/vul/")

变成

select id, "none" as vul members_repeater/vul/none 

谢谢

4

3 回答 3

4
:%s/_placeholder/\=split(getline("."),'"')[1]/g

这在这种情况下有效:

  • 每行只有一个引用部分(替换)
  • 引用部分可以在这一行的任何地方

例如:

select "ali" as name where _placeholder = _placeholder
union
select "sam" as name where _placeholder = _placeholder
select _placeholder where _placeholder = _placeholder "foo"
select _placeholder where "bar", _placeholder = _placeholder

进入

select "ali" as name where ali = ali
union
select "sam" as name where sam = sam
select foo where foo = foo "foo"
select bar where "bar", bar = bar

编辑

\=split(getline("."),'"')[1]
 |  |      |
 |  |      +--- get current line text
 |  |
 |  +------ split the line with " as separator, pick the middle part ([1])
 |
 |
 +---- using expression replacement

新编辑

所以你可以重新使用旧的例程:

:%s#_placeholder#\=split(split(getline("."),"vul/")[1]," ")[0]#g

vul/在您的行中只需要一个,但关键字后面可能有文本(以空格作为分隔符),例如:

select id, "_placeholder" as vul members_repeater/vul/none trashtrash

进入

select id, "none" as vul members_repeater/vul/none trashtrash

看这个例子:

在此处输入图像描述

于 2013-02-15T16:09:31.857 回答
1

特别是对于这些行,那将是

s/^\(.*\)"\([^"]*\)"\(.*\)_placeholder\ = _placeholder/\1"\2"\3\2 = \2/

说明: 匹配的\(和之间的表达式\)被捕获在 \1、\2 等中。因此,在这里进行的一种方法是捕获直到 的所有内容_placeholder,然后将其放回原处。诚然,有点难以理解。

该解决方案假定每一行的双引号中只有一个表达式。

于 2013-02-15T16:01:25.337 回答
1

如果知道的话,您可以轻松使用sed它,它允许您使用扩展的正则表达式:

example_with_no_link.txt:

from django.utils import unittest
from django.core import management
from app import subapp

vim 命令:

:%! sed -re "/django/ s/from (.*) import (.*)/from \2 import \1/"

该命令执行以下操作:
1. :%!:将所有行放入标准输出
2. :如果第 3行中sed -re "/django/有 'django' 。 :括号中的反向模式
s/from (.*) import (.*)/from \2 import \1/

在 sed 中,您用括号捕获搜索的单词并用\n.
输出重定向到 vim。

于 2013-02-15T16:55:53.120 回答