There is no simple way to get capture groups into other commands. They simply don't see them.
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.
:g/pattern/s//replacement is pretty much equivalent to
: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:
This replaces all occurrences of "pat" with "PAT". The same can be done with:
Which is two characters shorter!
\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.
: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.