[英]Search and replace with fields on VIM
I want to search for a string and replace with a second string that was contained in the first one. 我想搜索一个字符串,并替换为第一个字符串中包含的第二个字符串。 For example I have the following lines
例如我有以下几行
key1: foo
key2: bar
My regex that maches this lines the way I want is: 我正则表达式的正则表达式是:
^\s\+\w:.\+
I want to replace the whole lines by something like: 我想用以下内容代替整行:
foo -> key1
bar -> key2
How can I do it? 我该怎么做?
Vim uses \\1 \\2
etc as back references, so you ought to be able to use: Vim使用
\\1 \\2
等作为反向引用,因此您应该可以使用:
:%s/^\s\+\(\w\+\): \(\w\+\)/\2 -> \1/g
Breakdown: 分解:
^\\s\\+
: one or more spaces at the start of the string. ^\\s\\+
:字符串开头的一个或多个空格。 Use *
if there may be zero *
\\(\\w\\+\\)
: Capture group of word characters into \\1
\\(\\w\\+\\)
:将一组单词字符捕获到\\1
:
Literal colon and space :
文字冒号和空间 \\(\\w\\+\\)
: Another capture group for the second pair \\(\\w\\+\\)
:第二对的另一个捕获组 /\\2 -> \\1/
Replacement with back references. /\\2 -> \\1/
用反向引用替换。 Eliminates the leading whitespace, and swaps the two groups (here's the \\v
very magic version which will look a lot nicer and avoid tons of meta-character escaping): (这是
\\v
非常神奇的版本,它将看起来更好,并避免了大量的元字符转义):
:%s/\v\s+(\w+): (\w+)/\2 -> \1/g
我想出了:s
命令,
%s/\v\s*([^:]*):\zs.*/\1/
Alternative to substitution 替代替代
:%norm <<dWA -> ^]pbD
Note that ^]
is obtained by pressing <cv><esc>
请注意,
^]
是通过按<cv><esc>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.