Vi and Vim Search and Replace Operations – POFTUT

Vi and Vim Search and Replace Operations


Vim provides reach features for text and word search and replace operations. Sed and awk provides similar features to Vim but vim is text editor which makes it different from others.

Sample Text

During examples we will use following sample text.

# 
# The MySQL database server configuration file. 
# 
# You can copy this to one of: 
# - "/etc/mysql/my.cnf" to set global options, 
# - "~/.my.cnf" to set user-specific options. 
#  
# One can use all long options that the program supports. 
# Run program with --help to get a list of available options and with 
# --print-defaults to see which it would actually understand and use.

Search and Replace In Whole Document

The most popular use  case is search and replace in whole document. We will use search commands. In this example we will search with %s for database and change to DB in whole file with .

: %s/database/DB/g

Search and Replace In Current Line

We can shrink the scope to the current line where cursor locates. We will remove % from s search parameter. We will search for database and replace with DB

: s/database/DB/g

Ask Before Replace

Another useful feature of search and replace is asking or confirming before replace operation. We will add c after g option like below.We will search for string database and replace with DB

: %s/database/DB/gc

Search Only Whole Words and Replace

By default search and replace operation is done without looking whole word. Event is searched text is a part of word it will be replaced. We can only search in whole words by surrounding the search text with \< and \> like below. We will search base as a whole word.

: %s/\<database\>/DB/g

Search Case Insensitive and Replace

Vim search mechanism search case sensitive by default. We can turn of case insensitivity. We will provide i after g option. We will search for database as case insensitive and replace with DB

: %s/database/DB/gi

LEARN MORE  Php - Install Php In Linux and Create Development Environment

Leave a Comment