Ricardo Acras
Ricardo Acras

Reputation: 36254

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?

Upvotes: 1

Views: 378

Answers (3)

Peter Rincker
Peter Rincker

Reputation: 45177

Alternative to substitution

:%norm <<dWA -> ^]pbD

Note that ^] is obtained by pressing <c-v><esc>

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270775

Vim uses \1 \2 etc as back references, so you ought to be able to use:

:%s/^\s\+\(\w\+\): \(\w\+\)/\2 -> \1/g

Breakdown:

  • ^\s\+ : one or more spaces at the start of the string. Use * if there may be zero
  • \(\w\+\): Capture group of word characters into \1
  • : Literal colon and space
  • \(\w\+\): Another capture group for the second pair
  • /\2 -> \1/ Replacement with back references. 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):

:%s/\v\s+(\w+): (\w+)/\2 -> \1/g

Upvotes: 6

Kent
Kent

Reputation: 195269

I come up with this, :s command,

 %s/\v\s*([^:]*):\zs.*/\1/

Upvotes: 1

Related Questions