Vim - Capture strings on Search and use on Replace

10,151

Solution 1

Use \1... See the wiki here: http://vim.wikia.com/wiki/Search_and_replace

More explicitly:

%s:/#page-site-index \(.toolbar .items\)/#page-site-index \1, #page-site-login \1/g

Solution 2

try this command in your vim:

%s/\v#(page-site-index )(\.toolbar \.items)/&, #page-site-login \2/g

you could also use \zs, \ze and without grouping:

%s/#page-site-index \zs\.toolbar \.items\ze/&, #page-site-login &/g

keep golfing, if the text is just like what you gave in question, you could:

%s/#page-site-index \zs[^{]*\ze /&, #page-site-login &/g

Solution 3

You've already grouped the interesting parts of the regular expression via \(...\) in your attempt. To refer to these captured submatches inside the replacement part, use \1, \2, etc., where the number refers to the first (opened) capture group, from left to right. There's also \0 == & for the entire matched text. See :help /\1 for more information.

Share:
10,151
user1410363
Author by

user1410363

Updated on July 23, 2022

Comments

  • user1410363
    user1410363 almost 2 years

    I have a css selector such as:

    #page-site-index .toolbar .items {
    

    How do I capture the ".toolbar .items" part and use it on Replace part of Vim S&R, so this selector can turn into:

    #page-site-index .toolbar .items, #page-site-login .toolbar .items {
    

    Something like:

    %s:/#page-site-index \(.toolbar .items\)/#page-site-index (the captured string), #page-site-login (the captured string)/g
    

    Btw, I'm using the terminal version of Vim.

  • user1410363
    user1410363 about 11 years
    Thanks, but there's a lot of other selectors in this file and I would like to replace them all with a single command.
  • hek2mgl
    hek2mgl about 11 years
    Yes this is specific for the question. Need to see the whole file to give a general answer.
  • user1410363
    user1410363 about 11 years
    Thanks! I've just had to change the (.toolbar .items) to (.\+), but your answer pointed me to the right direction.
  • Evgeny
    Evgeny about 8 years
    the parentheses need to be backslashed
  • jtmarmon
    jtmarmon over 7 years
    to summarize: if you want to replace foobarbaz, fooquxbaz, fooanythingbaz with bar, qux, anything, do :%s /foo(.\+)baz/\1/g