Search and Replace text with Vim


Search and Replace with Vim
My main use of Search and Replace on vim would be for urls and country mirrors in my sources.list. If you find a particular mirror is running a bit slow (very common for me in Spain with the Spanish Debian/Ubuntu mirrors), then you can change all of them in one go to a faster mirror like this:

:%s/es.debian.org/fr.debian.org/g

This will replace all instances of the Spanish (es) Debian mirror for the (fr) French mirror which is usually faster. 

The :substitute command searches for text, and replaces it with different text. The g flag means global, each occurrence in the line is changed, rather than just the first.

Examples:
:s/foo/bar/g               Change each ‘foo’ to ‘bar’ in the current line.
:%s/foo/bar/g            Change each ‘foo’ to ‘bar’ in all lines.
:5,12s/foo/bar/g        Change each ‘foo’ to ‘bar’ for all lines from line 5 to line 12.
:’a,’bs/foo/bar/g         Change each ‘foo’ to ‘bar’ for all lines from mark a to mark b.
:.,$s/foo/bar/g           Change each ‘foo’ to ‘bar’ for all lines from line (.) to line ($).
:.,+2s/foo/bar/g         Change each ‘foo’ to ‘bar’ for line (.) and the two next lines (+2).
:g/^baz/s/foo/bar/g    Change each ‘foo’ to ‘bar’ in each line starting with ‘baz’.

Source: http://vim.wikia.com/wiki/Search_and_replace

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s