106 votes
Accepted

How to find and replace in Vim without having to type the original word?

I actually have a pretty similar workflow to yours, (copying and pasting blocks that are similar, then using :s to change variable names) especially when I'm writing lots of lines that are similar ...
DJMcMayhem's user avatar
  • 17.4k
25 votes

How to find and replace in Vim without having to type the original word?

The c_CTRL-R family of maps can improve your workflow quite a bit: You need not type variable names when using :s/, just use CTRL-R CTRL-W to insert the word under the cursor into the command line (...
Mass's user avatar
  • 13.9k
23 votes

How to replace each match with incrementing counter?

:let @a=1 | %s/search/\='replace'.(@a+setreg('a',@a+1))/g But beware, it will overwrite your register a. I think it is a little bit more straight forward than luc's answer, but maybe his is faster. ...
B.G.'s user avatar
  • 1,116
22 votes

How to replace only within visual selection?

There’s \%V for that, see :h %V: %V Match inside the Visual area. When Visual mode has already been stopped match in the area that gv would reselect. This is a /zero-width match. To make sure the ...
dessert's user avatar
  • 345
22 votes
Accepted

How can I repeat last substitution and with the same flags

This is exactly what :&& does: *:&&* [&] Must be the first one: Keep the flags from the previous substitute command. Examples: > :&&...
Naumann's user avatar
  • 2,739
21 votes

Replace a string without changing case?

This can be handled by the :Subvert from the abolish plugin: One time I had an application with a domain model called "facility" that needed to be renamed to "building". So, a simple search and ...
mMontu's user avatar
  • 6,600
20 votes
Accepted

Multiple choice substitute?

The implementation of :s//c is fixed; what you're looking for is replacement with a Vimscript expression (:help sub-replace-expr). You can query a single-digit via getchar(), or prompt for longer ...
Ingo Karkat's user avatar
  • 17.7k
20 votes
Accepted

How to run a substitute command on only a certain part of the line

Yes, this is a long answer. That's because I try to cover the sometimes intimidating sub-replace expression as clearly as I can. Don't be frightened...please dive in! :) This can be looked at as a ...
B Layer's user avatar
  • 19.5k
19 votes
Accepted

Vim global substitution doesn't substitute all matches in a line

Maybe you, or a plugin, had enabled the option 'gdefault'. This option adds the flag g automatically whenever you perform a substitution. So, when you manually add the flag g while 'gdefault' is ...
user9433424's user avatar
  • 6,118
18 votes
Accepted

Can I make :s operate only on the last match of the line?

I would use \zs :%s/.*\zspattern/replacement/ A little bit of explanation: . represents any single character * represents greedy matching (as many as possible) In Vim you can use zero-width ...
ryuichiro's user avatar
  • 1,171
18 votes
Accepted

Replace a string without changing case?

Michaels Geddes' plugin keepcase (GitHub) has all you need: :%SubstituteCase/\cterm/word/g Other syntax elements from :substitute are also supported.
Luc Hermitte's user avatar
18 votes

How to replace each match with incrementing counter?

You need substitution with a state. I remember having provided a (/several?) complete solution for this kind of problems on SO. Here is another way to proceed (1). Now, I'll proceed into 2 steps: a ...
Luc Hermitte's user avatar
17 votes
Accepted

Substitute second occurence on line

In general you can match the Nth occurrence of something using \zs and \{N}. There's an example given at :help \zs. In your case the command would be: :%s/\(.\{-}\zstemp\.\)\{2}//
Antony's user avatar
  • 2,550
16 votes
Accepted

Delete all consecutive duplicates

I think the following command should work : :%s/^\(.*\)\(\n\1\)\+$/\1/ Explanation : We use the substitution command on the whole file to change pattern into string : :%s/pattern/string/ Here ...
saginaw's user avatar
  • 6,706
16 votes
Accepted

What is the best way to re-factor a variable name in vim?

You can just use the usual workflow search and replace: /original cwreplaced n.n. You can take also advantage of the gn motion: /original<CR> cgnreplaced<ESC> ..... cgn will change the ...
nobe4's user avatar
  • 15.9k
15 votes

Substitute with pure vimscript (without `:s`)

Here is a simplistic implementation of your function, written with substitute(): function! AddSpaceBeforeEqualInWholeBuffer() let l = 1 for line in getline(1,"$") call setline(l, ...
romainl's user avatar
  • 39.1k
15 votes
Accepted

Replace a series of asterisk bullet points with a numbered list

You could try the following command: :let c=0 | g/^* /let c+=1 | s//\=c.'. ' First it initializes the variable c (let c=0), then it executes the global command g which looks for the pattern ^* (a ...
saginaw's user avatar
  • 6,706
15 votes
Accepted

How can I run :substitute on only part of the line and not all of it?

You could use the following solution: First use v$ to select the text from the cursor to the end of the line. Then use the following command: :s/\%V\ /_/g The \%V indicate to change the text in the ...
statox's user avatar
  • 49.3k
15 votes
Accepted

Perform previous substitution for different selection with single keystroke

I think you want to do @: which replays the last ex command. See :h @: Note that this command can be called from normal mode and from visual mode. Also in this case it is not useful but you can also ...
statox's user avatar
  • 49.3k
15 votes
Accepted

What is the rationale for \r and \n meaning different things in s command?

At the most basic level, there's already an asymmetry between the search and replace portions of :substitute because the former is a regular expression and the latter is text, with specific additional ...
jamessan's user avatar
  • 10.9k
15 votes

How to find and replace in Vim without having to type the original word?

There are a couple more methods that (to my surprise!) haven't been mentioned yet. Using the gn Command gn works like the n command, except that in addition to jumping to the match, it enters visual ...
Rich's user avatar
  • 31.3k
14 votes

Substitute second occurence on line

This is much easier done with sed: sed 's/\.temp\././2' With Vim you need non-greedy matching, and it isn't easy to extend the method to replacing the 3rd, 4th, etc. occurrence of temp. But it can ...
Sato Katsura's user avatar
  • 3,999
14 votes

What is the most efficient way to invert two words?

Posting this so it can have an answer on our SE, but this is this source with full explanation. Here's a good way to use a single regex to do multiple substitutions: :%s/foo\|bar/\={'foo':'bar','bar'...
Tumbler41's user avatar
  • 7,706
13 votes

Can I do an interactive :substitute (search & replace)?

My favorite interactive substitution is to search using / and go through the matches using n. Then select match using gn and then s to substitute the text with whatever I like. And repeat by moving ...
Neaţu Ovidiu Gabriel's user avatar
13 votes

Substitute with pure vimscript (without `:s`)

The reason it is warning you about unintended side effects is because :substitute does move the cursor and overwrite the previous search (if used outside of a function). However, this does not mean ...
EvergreenTree's user avatar
13 votes
Accepted

Find and replace all numbers with 0?

Based on the help file, and the Vim Wikia page on Search and replace :%s/[0-9]\+\.[0-9]\+\|[0-9]\+/0/g :%s - start a command with the range of the entire file, %, to substitute, the following ...
Herb's user avatar
  • 1,203
12 votes

Delete all consecutive duplicates

Try the following: :%s;\v^(.*)(\n\1)+$;\1; As with saginaw's answer, this uses Vim's :substitute command. However, it takes advantage of a couple of extra features to improve readability: Vim lets ...
Bloodgain's user avatar
  • 221
12 votes
Accepted

Replace Nth Occurrence Using Substitute

Peter's answer achieves the result that you want, but not necessarily the question that you asked. This regular expression will match the Nth occurrence of your PATTERN: \(.\{-}\zsPATTERN\)\{N} To ...
Zach Ingbretsen's user avatar
12 votes
Accepted

How can I execute multiple optional substitute commands in one line?

Add the e flag to your :s commands: :%s#from1#to1#ge | %s#from2#to2#ge From the flag's entry at :help :s_flags: [e] When the search pattern fails, do not issue an error message and, in ...
Martin Tournoij's user avatar
12 votes

How to run a substitute command on only a certain part of the line

Since you mentioned visual mode... You can also use the \%V match to only match inside the current visual selection (or last one, if not in visual mode.) Using \%V would allow you to use the same ...
filbranden's user avatar
  • 28.4k

Only top scored, non community-wiki answers of a minimum length are eligible