Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use find and replace on a wildcard string in VIM?

For example, I have a bunch of values with a common prefix and postfix, such as:

fooVal1Bar;  fooVal2Bar;  fooVal3Bar; 

In this case, all variable names begin and end with foo and end with Bar. I want to use a find and replace using the random variable names found between foo and Bar. Say I already have variables Val1, Val2, Val3, and Val1Old, Val2Old, and Val3Old Defined. I would do a find a replace, something along the lines of:

:%s/foo<AnyString>Bar/foo<AnyString>Bar = <AnyString> + <AnyString>Old 

This would result in:

fooVal1Bar = Val1 + Val1Old;  fooVal2Bar = Val2 + Val2Old;  fooVal3Bar = Val3 + Val3Old; 

I hope it's clear what I want to do, I couldn't find anything in vim help or online about replacing with wildcard strings. The most I could find was about searching for wildcard strings.

like image 227
dwcanillas Avatar asked Apr 26 '12 15:04

dwcanillas


People also ask

How do you do a search and replace string in Vim?

Search for text using / or for a word using * . In normal mode, type cgn (change the next search hit) then immediately type the replacement. Press Esc to finish. From normal mode, search for the next occurrence that you want to replace ( n ) and press . to repeat the last change.

When would you use a wildcard in a find and replace operation in Word?

Wildcards are used to represent the characters or sequences of characters in that string. Because different combinations of characters can be represented by a variety of wildcard combinations, there is often more than one way of identifying a particular string of text within a document.


1 Answers

I believe you want

:%s/foo\(\w\+\)Bar/& = \1 + \1\Old/ 

explanation:

\w\+ finds one or more occurences of a character. The preceeding foo and following Bar ensure that these matched characters are just between a foo and a Bar.

\(...\) stores this characters so that they can be used in the replace part of the substitution.

& copies what was matched

\1 is the string captured in the \(....\) part.

like image 121
René Nyffenegger Avatar answered Sep 22 '22 17:09

René Nyffenegger