Here you go:
:g/foo/t.|s//bar
Decomposing:
:g/foo/ " start a global command applied on all lines matching 'foo'
t. " duplicate the current line (the cursor is now on the new line)
| " chain a new command
s//bar " substitute the last searched element with 'bar'
Because the g
command will update the search pattern, so you can omit the pattern to replace in the substitute command. (ref: :h :g
, search for search pattern
).
Older version:
:g/foo/norm! yyp:s/foo/bar^M
Decomposing:
:g start a global command
/foo/ apply only on lines having 'foo'
norm! execute a normal command
yyp duplicate the line
:s//bar replace foo with bar on the line (the duplicated one)
^M add enter to execute the substitution
To insert the ^M
press Ctrl+v and enter.
Note: I originally came up with the "older" version, before I learned about the t
command. I'll leave it but I won't recommend using it. The first one is cleaner more straightforward.