12

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.

4 Answers 4

23

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I've just had to change the (.toolbar .items) to (.\+), but your answer pointed me to the right direction.
the parentheses need to be backslashed
to summarize: if you want to replace foobarbaz, fooquxbaz, fooanythingbaz with bar, qux, anything, do :%s /foo(.\+)baz/\1/g
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

Comments

2

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.

Comments

0

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....

2 Comments

Thanks, but there's a lot of other selectors in this file and I would like to replace them all with a single command.
Yes this is specific for the question. Need to see the whole file to give a general answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.