Searching and highlighting in vi editor

In this post we will look into at the ways in which we can search in a program using the VI editor.

The searching always happens in the command mode so if you want to search for a string or a pattern in the program, first step is to go to the command mode by pressing “esc”

Let us take a simple hello world program as an example.
#includemain() { printf(“Hello world”); printf(“world”); }

Let us say we come across the string printf once and want to search all the occurrences of printf after the current cursor position, then just move the cursor on printf and press “*”. The cursor will automatically move to the next occurrence of printf and on each press of “*” it will move to the next occurrence of printf.

To search backwards, that is behind the current cursor position place the cursor on printf and press “#”. The cursor will move to the previous occurence of the search string. The second way of searching is
Go to command mode and type /

any thing that follows the “/” will be taken as the search string.

Then keep pressing “n” to move to the next occurrences of the search string. If you want to move back in the document, that is search for occurrences of the string before the current cursor position use the shift “n” , i.e “N” .
To see all the matching strings at the same time we can highlight all the matched strings by setting the option hlsearch i.e.

:set hlsearch

All the items which matched the previous search string will get highlighted. To remove the highlight run the command

:nohlsearch

To make the seach case insensitive we need to set the option “ignorecase” i.e

set ignorecase

The search can be made case insensitive by adding \c to the search string, i.e

/\c/

The search can also be restrcted to specific lines. To restict the search only to a single line we need to use \%numl along with the search string. To restrict the search for strintg printf to 20th line we need to use

/\%20l\printf/

To restinct the search to lines after 20th line

/\>%20l\printf/

To restinct the search to lines between 20th line and 30th lines

/\>%20l\%


Tags: ,
Copyright 2017. All rights reserved.

Posted January 17, 2013 by Tux Think in category "Linux