Buksy
Buksy

Reputation: 12228

Vi, replace text

I have text like this

template
template
template_results
template

And I need to replace it to this

template_form
template_form
template_results
template_form

How can I replace every match of template that is not followed by _ character in Vi?

I tried it like this

:%s/template[^_]/template_form    - Pattern not found
:%s/template\[^_]/template_form   - Pattern not found
:%s/template[_]/template_form     - This works, but the pattern is opposite of what I need

Thank you :)

Upvotes: 1

Views: 507

Answers (3)

GregHNZ
GregHNZ

Reputation: 8969

You're trying to specify template then nothing. So the trick is to use the end of line specifier $

:%s/template$/template_form/g

The first one doesn't work because this [^_] matches any single character other than underline, but not no characters (or end of line, apparently).

Upvotes: 2

guido
guido

Reputation: 19194

Use negative lookahead:

:%s/template\(_\)\@!/template_form/gc

This means match any "template" not followed (\@!) by any "_"

See: :help /zero-width

Upvotes: 2

Codie CodeMonkey
Codie CodeMonkey

Reputation: 7946

This is easy in VIM, but sticking to what I BELIEVE to be in vanilla VI, you could do

:%s/template$/template_form/

This assumes that each line is followed by a end-of-line. If not, try:

:s/template\(\s\|$\)/template_form/

I don't know if the "magic" is right for your flavor of VI, but this matches "template" followed by whitespace or the end-of-line.

Upvotes: 0

Related Questions