Basic Linux Tutorial
Computer Tutorial

Search and Replace



Search and Replace

Search and replace is a necessary editing feature found in all good editors. If you want to find a text pattern in Vi, you can use the /text command, where text is the string you want to search. This command searches the text in the forward direction from the current cursor position. You can search in the backward direction if you replace / with ? in the command. To repeat the search once you find a string, just use / or ? without typing the string again.
You can also replace text after a search is made. For example, if you want to replace the word "Zen" with "Generalnote" you can use the command :s/Generalnote/Zen/ to search for the next occurrence of "Zen" and then replace it with "Generalnote" You can use the search-and-replace feature in as many lines as you want or in all of the file.

Text Replacement Commands

Command Effect
/text Search text in forward direction starting from current cursor location
?text Search text in backward direction starting from current cursor location
/ Repeat previous search in forward direction
? Repeat previous search in backward direction
n Repeat search in the same direction
N Repeat search in the opposite direction
:s/oldtext/newtext Search oldtext in the forward direction and replace it with newtext
:m,ns/oldtext/newtext Search oldtext in the forward direction from line m to line n and replace it with newtext
:s/oldtext/newtext/g Search oldtext in the entire file and replace it with newtext
/ text If you put a space between the / and the text to be searched, only whole words are searched
/^text Search text only in the beginning of a line
/text$ Search text only in the end of a line
/(More than one word) Use parenthesis to search multiple words