How to replace one line in vim?

2

1

I have an ipv6 hosts file. No I want to add a comment symbol # to each line that having "google.com.hk".

How could I do this in vim? I thought it would be something like %s/^.*google\.com\.hk/^#???/.

thanks.

Jichao

Posted 2010-08-28T12:30:14.517

Reputation: 5 245

Answers

6

Use & in the replacement text to stand for the whole original string:

%s/^.*google\.com\.hk/#&/

or, to avoid replacing things like not-google.com.hk and google.com.hk.example.com:

%s/^.*[ .]google\.com\.hk\( \|$\)/#&/

Alternatively, use the g command to apply an s command to all matching lines:

g/[ .]google\.com\.hk\( \|$\)/ s/^/#/

Gilles 'SO- stop being evil'

Posted 2010-08-28T12:30:14.517

Reputation: 58 319

what about \< and \> word boundary assertions? – Philip Potter – 2010-08-28T14:00:19.707

@Philip: They would help only if . and - were word constituent characters, which is not the case by default (and would render b/e/w not usefully different from B/E/W). – Gilles 'SO- stop being evil' – 2010-08-28T14:17:10.607

2

Like this:

%s/\(^.*google\.com\.hk\)/# \1/

This tells VIM to search for what's in the parentheses, in this case ^.*google\.com\.hk, and put that into the \1 variable. Then you replace all that you found before with # followed by \1.

Alternatively, you could do:

%s/^.*google\.com\.hk/# &/

Where the & is shorthand for whatever was just matched

Nathan Fellman

Posted 2010-08-28T12:30:14.517

Reputation: 8 152