每行的VIm替换基于同一行上的另一个单词的单词

时间:2013-02-15 15:57:09

标签: vim

如何在VIM中实现以下功能

substitute/regex_this_word/regex_with_another_word_from_the_same_line

e.g

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

e.g2

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 

感谢

3 个答案:

答案 0 :(得分: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

见这个例子:

enter image description here

答案 1 :(得分:1)

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

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

解释:匹配的\(\)对之间的表达式是\ 1,\ 2等中的捕获。因此,这里继续进行的一种方法是捕获{{1}之前的所有内容。然后把它放回去了。不可否认,有点难以理解。

该解决方案假设每行上只有一个双引号表达式。

答案 2 :(得分: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. :%!:将所有行放入stdout中 2. sed -re "/django/:如果行中有'django' 3. s/from (.*) import (.*)/from \2 import \1/:括号中的反转模式

在sed中,您可以使用括号捕获搜索到的单词,并使用\n进行书写 输出重定向到vim。