David.Chu.ca
David.Chu.ca

Reputation: 38634

How to use the matched text in the replacement text in Vim

I have a block of codes with timestamp in front of each line like this:

12/02/2010 12:20:12 function myFun()
12/02/2010 12:20:13 {....

The first column is a date time value. I would like to comment them out by using Vim, thus:

/*12/02/2010 12:20:12*/ function myFun()
/*12/02/2010 12:20:13*/ {....

I tried to search for date first:

/\d\d\/\d\d\/\d\d\d\d \d\d:\d\d:\d\d

I got all the timestamps marked correctly. However When I tried to replace them by the command:

%s/\d\d\/\d\d\/\d\d\d\d \d\d:\d\d:\d\d/\/*\d\d\/\d\d\/\d\d\d\d \d\d:\d\d:\d\d*\// 

I got the following result:

/*dd/dd/dddd dd:dd:dd*/ function myFun()
/*dd/dd/dddd dd:dd:dd*/ {....

I think I need to name the search part and put them back in the replace part. How I can do it?

Upvotes: 0

Views: 373

Answers (4)

frogstarr78
frogstarr78

Reputation: 868

I would actually not us a regex to do this. It takes too long to enter the correct formatting. I would instead use a Visual Block. The sequence works out to be something like this.

<C-V>}I/* <ESC>
3f\s
<C-V>I */

I love regex, and don't want to knock the regex solutions, but find when doing things with pre-formatted blocks, that this is easier, and requires less of a diversion from the real task, which isn't figuring out how to write a regex.

Upvotes: 4

ghostdog74
ghostdog74

Reputation: 342273

:%s/^\([0-9/]* [0-9:]* \)\(.*\)/\/*\1*\/ \2/

Upvotes: 0

DigitalRoss
DigitalRoss

Reputation: 146053

I suppose I would just do something like:

:%s-^../../.... ..:..:..-/* & */-

Upvotes: 6

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

%s/\d\d\/\d\d\/\d\d\d\d \d\d:\d\d:\d\d/\/*&*\// 

Upvotes: 2

Related Questions