To learn about pattern matching, we will ensure that the pattern that we will search for is highlighted when the pattern searched for is found. The configuration file for vi is /etc/vimrc.In the vi editor, use the following commands for various options:
Sr.
Commands
Description
1
:set hlsearch
Highlights the search pattern
2
:se[t] showmode
Shows when you are in insert mode
3
:se[t] ic
Ignores case when searching
4
:set noic
Shows a case-sensitive search
The user should open the file in vi, press the Esc button so that it enters command mode, and then type colon, followed by these commands. The following are the commands for pattern search and replace:
Sr.
Commands
Description
1
/pat
This searches for the patternpatand places the cursor where the pattern occurs
2
/
This repeats the last search
3
:%s/old/new/g
Globally, all the occurrences ofoldwill be replaced bynew
4
:#,#s/old/new/g
#,#should be replaced with the numbers of the two lines (say between line numbers3and6), for example,3,6s/am/was/g
The following is an example of a regular expression for replacing Tom with David:
:1,$s/tom/David/g // from line 1 to end ($), replace tom by David
:1,$s/<[tT]om>/David/g // start and end of word < >
This is another example of a regular expression. Create the love.txt file, as follows:
Man has love for Art
World is full of love
Love makes world wonderful
love looove lve
love
Love love lover loves
I like "Unix" more than DOS
I love "Unix"/
I said I love "Unix"
I love "unix" a lot
Use the following commands for testing pattern-searching facilities:
Command
Description
:set hlsearch
This will highlight the search pattern, when it is found
/love/
This will highlight any text matching withlove. Usenfor forward andNfor backward in the next search
/^love/
This will highlight the line starting withlove
/love$/
This will highlight the line ending withlove
/^love$/
This will highlight a line containing only the wordlove
/l.ve/
This will highlight any character match for.
/o*ve/
This will highlightlove,loooove, andlve
/[Ll]ove/
This will search for patterns Love and love
/ove[a-z]/
This will highlight any matching character in theatozrange
/ove[^a-zA-Z0-9" "]/
Except for alpha-numeric characters, this will match punctuation marks such as , ; : and similar
:%s/unix/Linux/g
This will replaceunixwithLinux
:1,$s/unix/Linux/g
This will replaceunixwithLinuxfrom line1to the end ($)
:1,$s/<[uU]nix>/Linux/g
This will start and end of word< >
/^[A-Z]..$
This will highlight a line starting with an uppercase letter, two chars and then end of line
/^[A-Z][a-z ]*3[0-5]/
This will highlight any line ending with30to35
/[a-z]* ./
This will highlight any line with lowercase and ending with.
