Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace just the capture group 2 in VIM with some text

Tags:

regex

vim

vi

I am using below regex to abc1,cde2,efg3 replace with hello but somehow it's not working

 :%s/\(\d\{2}:\d\{2}:\d\{2\}\s\)\([A-z0-9]*\)/hello/gc

Mar 17 02:25:01 abc1 micro: Starting use.slice.

Mar 17 02:25:01 cde2 micro: Starting use.slic

mar 17 02:25:01 efg3 micro: Starting use.slic

like image 417
user3438838 Avatar asked Oct 23 '17 16:10

user3438838


2 Answers

You can use this substitute command in vim:

%s/\v(\d{2}:\d{2}:\d{2}\s+)[a-zA-Z0-9]+/\1hello/g
  • Here \v is used for very magic that avoids escaping as per older BRE syntax.
  • \1 is back-reference of captured group #1
like image 136
anubhava Avatar answered Nov 09 '22 23:11

anubhava


You can use \zs to set where the match will start in the substitution.

:%s/\d\{2}:\d\{2}:\d\{2\}\s\zs[A-z0-9]*/hello/gc

For more help see :h /\zs

like image 36
Peter Rincker Avatar answered Nov 09 '22 23:11

Peter Rincker