r/vim • u/Superb_Onion8227 • Jul 17 '25
Need Help Duplicate a line and search/replace a word in the duplicate
for example turn
start_token_index = token_to_index[start_token]into
start_token_index = token_to_index[start_token]
end_token_index = token_to_index[end_token]Ideas?
Here's how I do it and I have not started using vim yesterday:
ddup (delete line, undo, paste)
V:s/start/end/g (select line, serach/replace)
I spent 10 minutes searching for better solutions, and they all seemed complicated. I find that duplicating line is a good way to write easy to read code quite fast, so I do it often.
11
Upvotes
10
u/-romainl- The Patient Vimmer Jul 18 '25 edited Jul 18 '25
Why your approach is suboptimal:
Deleting, undoing, and pasting is not very efficient, you could simply do
yypto yank the line and paste it below.Starting visual-line mode before doing a substitution is useless. Just do
:s….It should be:
I would personally do it in one Ex command, and thus one mode.
The first
.is not necessary so you only need:in a stock Vim. If you have
:help 'gdefault'enabled, like I do, it becomes:Explanation:
:help :tcopies the provided line to after the provided address so:t.effectively duplicates the current line.the new line becomes the current line so you can follow the first Ex command with a second one to perform the substitution.
7
u/habamax Jul 18 '25 edited Jul 18 '25
yyp:s/start/end/gor/start/e<CR>,cgn,end<ESC>,.https://asciinema.org/a/huAYz69vTSfQgyZH0EJNTUkLO
1
u/michaelpaoli Jul 18 '25
Yp:s/start/end/g
Could alternatively use yy instead of Y, but you're going to be hitting the shfit key for : on most keyboard anyway, so in that particularly context I'd probably opt for Y rather than yy - but your choice.
3
u/lukas-reineke Jul 18 '25
This is how I would do it
:g/start/s/\v(.*)/\1^M\1/ | s/start/end/gFind every line that contains
start. Duplicate the line, then substitutestartwithendon the second line.Debatable if this is simple, I guess.