user1971455
user1971455

Reputation: 433

vi editor, how to replace third match on every line

Using the vi editor, I want to replace the third occurrence of ":" on each line to ":1:". What is the correct search and replace command?

Thanks

Upvotes: 0

Views: 46

Answers (1)

John Bollinger
John Bollinger

Reputation: 181734

That would be

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

where

% means all lines;

s is the substitution command;

/\([^:]*:[^:]*:[^:*]\):\(.*\)/ matches three colon-delimited sequences of any number (including zero) of non-colons, starting at the beginning of the line, followed by a colon and the remainder of the line, capturing everything before and everything after the third colon; and

/\1:1:\2/ (where the lead slash is also the trailing slash of the pattern) is the replacement string, with \1 and \2 representing the first and second captured groups, respectively, and :1: being literal text.

Upvotes: 1

Related Questions