TL;DR
There is no simple way to get capture groups into other commands. They simply don't see them.
About the :s
command
As many vim users know, :s
is the :substitute
command, and it deals in vim's flavor of regular expressions.
As many "frequent flyers" know, :s
can re-use previous patterns by not providing them. This has lead me to a workflow wherein I will search (/
), perfect my pattern, and then "replace" with :%s//<replace>/g
--I'm re-using the pattern I searched for.
Global substitute
:g/pattern/s//replacement
is pretty much equivalent to :%s/pattern/replacement/
--by default, :s
only performs substitutions on lines where pattern matches. By using :g
instead, you're performing the narrowing of lines first and then invoking the replace. But either way, it accomplishes the same goal.
From the help docs:
The global command sets both the last used search pattern and the last used
substitute pattern (this is vi compatible). This makes it easy to globally
replace a string:
:g/pat/s//PAT/g
This replaces all occurrences of "pat" with "PAT". The same can be done with:
:%s/pat/PAT/g
Which is two characters shorter!
Why \1
works here, and not anywhere else
As I just mentioned, :s//replacement
will re-use the last search pattern. See :help last-pattern
for more.
Fortunately, the :g
command also sets this "last pattern".
So, we can translate:
:g/aaa\(.*\)/s//X\1X <=> :g/aaa\(.*\)/s/aaa\(.*\)/X\1X
The capture group exists during the substitute. But,
:g/aaa\(.*\)/echo \1 <=> :g/aaa\(.*\)/echo \1
There's no capturing done in the second part of the global command. Vim just runs the literal :echo \1
on every line matching the pattern.
s
because youre reusing the old pattern fromg
. will write an answer later.