Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

searching and replace without consuming what you are searching for

Tags:

regex

vim

Say I have lines like this:

'alpha' 123 
'beta' 678
'alpha' 998
'gamma' 212

And using the search & replace regex in VIM, turn it into this:

'alpha' 123 : alpha
'beta' 678 : beta
'alpha' 998 : alpha
'gamma' 212 : gamma

Basically, the search won't be replacing what it's searching for, but instead just using it for something else. In my head, this should work:

:g/'\(.*\)'/s/$/: \1/g

But that didn't do it. How do I not consume what I'm searching for but retain it for use?

like image 692
Bromide Avatar asked Apr 22 '13 16:04

Bromide


1 Answers

The initial g for the match does not capture for replacement; it is only used for grouping for the search. Instead use this, which is a little simpler too:

%s/'\(.*\)'.*/& : \1/

The & replaces everything that was matched.

like image 166
Explosion Pills Avatar answered Sep 28 '22 15:09

Explosion Pills