user1410363
user1410363

Reputation: 187

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.

Upvotes: 12

Views: 13811

Answers (4)

Lucas
Lucas

Reputation: 14909

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

Upvotes: 23

Ingo Karkat
Ingo Karkat

Reputation: 172510

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.

Upvotes: 2

Kent
Kent

Reputation: 195029

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

Upvotes: 2

hek2mgl
hek2mgl

Reputation: 157947

First type the : the get into command mode. Then issue the following command:

%s/#page-site-index .toolbar .items/#page-site-index .toolbar, #page-site-login
.toolbar .items/

Don't care about the formatting, its because of the stackoverflow markdown parser....

Upvotes: 0

Related Questions