Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim - Capture strings on Search and use on Replace

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.

like image 773
user1410363 Avatar asked Mar 27 '13 15:03

user1410363


3 Answers

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
like image 181
Lucas Avatar answered Nov 12 '22 03:11

Lucas


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
like image 41
Kent Avatar answered Nov 12 '22 04:11

Kent


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.

like image 29
Ingo Karkat Avatar answered Nov 12 '22 03:11

Ingo Karkat