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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With