How To Search To Find A Word In Vim Or Vi Text Editor - PhoenixNAP

Introduction

Vim and its older counterpart, Vi, are widely used text editors. Both are open-source and available on most Linux and macOS versions. Searching in Vim/Vi is a common and useful task that allows you to navigate through large files easily.

This tutorial will show you how to search in Vim/Vi via practical examples.

How to search in Vim and Vi - a tutorial.

Prerequisites

  • A system running Linux or macOS.
  • Access to the terminal.

Vim and Vi Search Commands

This section covers the available search commands in Vi/Vim. Make sure you are in Normal Mode before you start searching. Normal mode allows in-text navigating while using the editor commands. Vi and Vim open a file in normal mode by default.

Switch back to normal mode from any other mode with Esc.

Basic Search Commands in Vim and Vi

The basic search commands in Vim and Vi allow users to quickly locate keywords, phrases, or specific patterns within a single file. These commands are essential for navigating large files as they save time by instantly jumping to relevant content. You can search forward or backward, find repeated instances, or focus on a specific term.

The table below summarizes the basic search commands available in Vim and Vi:

CommandDescription
/patternSearches forward for pattern from the current cursor position.
?patternSearches backward for pattern from the current cursor position.
nMoves to the next occurrence of the last searched pattern.
NMoves to the previous occurrence of the last searched pattern.
*Searches forward for the word under the cursor.
#Searches backward for the word under the cursor.
:nohClears search highlighting.
<C-g>Displays the number of matches in the file.
/\<word\>Searches for entire words.

Advanced Search Commands in Vim and Vi

Advanced search commands in Vim and Vi enable users to utilize powerful pattern-matching and substitution features. These commands are ideal for more complex tasks, such as bulk edits, searching with regular expressions, or running specific commands on all matching lines.

Advanced search options allow you to customize searches to be case-insensitive, perform conditional replacements, and even execute shell commands.

The table below provides a list of advanced search commands in Vim and Vi:

CommandDescription
:/pattern/pPrints lines matching pattern without changing the cursor position.
:%s/pattern/replacement/gSubstitutes pattern with replacement throughout the file.
:%s/pattern/replacement/gcSubstitutes with confirmation for each match.
:g/pattern/commandExecutes a command on all lines matching pattern.
/\cpatternSearches for pattern case-insensitively.
/\vpatternEnables 'very magic' mode for a more readable regular expression syntax.

Combining Vim and Vi with Other Commands and Programs

Vim and Vi can integrate with external commands and programs to provide even more flexibility and functionality in searches. Combine search commands with tools like grep or use Vim's quickfix and location lists to extend searches across multiple files, manage lists of results, and run shell commands directly from within the editor.

Vim's integration with other commands is particularly useful for developers and administrators working across large codebases or system files. It facilitates streamlined searches and efficient management of complex tasks.

The table below outlines commands that can be combined with other programs:

CommandDescription
:grep pattern fileSearches for pattern in a specified file and loads matching results in the quickfix window.
:vimgrep /pattern/ *<em>/</em>.txtSearches for pattern in all .txt files in the current directory and subdirectories.
:copenOpens the quickfix window to display search results.
:lvimgrep /pattern/ fileSimilar to :vimgrep, but uses the location list instead of quickfix.
:helpgrep patternSearches for pattern in Vim help documentation.
:execute 'grep' shell-commandRuns a shell grep command and brings the output into Vim.

Searching in Vim and Vi: Examples

This section provides practical examples for using the Vi/Vim editor to search through files.

Search Forward For Next Result

To search forward, use the command:

/pattern

Replace pattern with the item(s) you want to find. For example, to search for all instances of the pattern root, do the following:

1. Press Esc to make sure Vim/Vi is in normal mode.

2. Type the command:

/root

The text editor highlights the first pattern instance after the cursor. In the image below, the result is part of a word that contains the specified pattern. This is because the command does not specify to search for whole words.

Search forward for a pattern in Vim.

From this position, select Enter and:

  • Jump to the next instance of the pattern in the same direction with n.
  • Skip to the next instance of the pattern in the opposite direction with N.

Search Backward for Word

To search backward, use the command below:

?pattern

Replace pattern with the item(s) you want to find. For example, to search for all instances of the pattern nologin, do the following:

1. Press Esc to make sure Vim/Vi is in normal mode.

2. Type the command:

?nologin

Vim/Vi highlights the first instance of the specified pattern before the cursor.

Search in Vi/Vim backward.

Hit Enter to confirm the search. Then, you can:

  • Move to the next instance of the pattern in the same direction with n.
  • Jump to the next instance of the pattern in the opposite direction with N.

Search for Current Word

The current word is the word where the cursor is located. Instead of specifying the pattern and prompting Vim/Vi to find it, move the cursor to a word and instruct it to find the next instance of that word.

Follow the steps below:

1. Press Esc to make sure you are in normal mode.

2. Move the cursor to the word you want to search.

3. From here, you can:

  • Search for the next instance of the word with *.
  • Search for the previous instance of the word with #.

Each time you press * or #, the cursor moves to the next/previous instance.

Search for Whole Words

To search for whole words, use the command below:

/\<word\>

Replace word with your search term. The text editor only highlights the first whole word precisely as specified in the command.

For example:

Searching and finding a whole word in vim.

Open File at Specific Word

Vim (and Vi) can open files at a specific word, allowing you to skip a step and go directly to the searched term.

To open a file at a specific word, use the command:

vim +/word [file_name]

or

vi +/word [file_name]

For example, to open the /etc/passwd file where it first uses the term root, run the command below:

vim +/root /etc/passwd

The text editor opens the file, and the first line it displays is the one containing the term root, as in the image below:

example of opening a file in vim at a specific word

Note: An alternative to opening a file at a specific word is opening a specific line number. See how to show or hide line numbers in Vi/Vim.

Case Insensitive Search

By default, Vi(m) searches are case-sensitive. For example, if you search for the term /user it doesn't show results with the capitalized U (i.e., User).

There are several ways to make Vim/Vi case insensitive.

  • To search for a specified word with the case insensitive attribute, run the command:
/\c<word>

The \c attribute instructs Vi(m) to ignore case and display all results.

  • An alternative is to set Vim to ignore case during the entire session for all searches. To do so, run the command below:
:set ignorecase
  • Lastly, the configuration file can be modified for the text editor to ignore case permanently. To do so, follow the steps below:

1. Open the ~/.vimrc configuration file.

nano ~/.vimrc

2. Add the following line to the file:

:set ignorecase

3. Save and exit the file.

All searches performed in Vi/Vim will now ignore case.

Highlight Search Results

Vi(m) has a useful feature that highlights search results in the file. To enable highlighting, type the following command in the text editor:

:set hlsearch

To disable this feature, run:

:set !hlsearch

Note: Vim color schemes are another useful feature for practical syntax highlighting. To learn more, see how to change and use Vim color schemes.

Search History

Vi(m) keeps track of search commands used in the session. Browse through previously used commands with ? or / and use the up and down keys to scroll through the history.

Search and Replace Across File

Use the syntax below to find and replace text throughout an entire file:

:%s/oldword/newword/g
  • Replace oldword with the text or pattern you want to replace.
  • Replace newword with the replacement text.
  • The g flag ensures all occurrences in each line are replaced.

For example, to replace all instances of debug with log, run:

:%s/debug/log/g

To confirm each replacement before it occurs, add the c flag:

:%s/debug/log/gc

Search Within Specific Range of Lines

You can limit search and replace operations to a specific range of lines. It is particularly useful when you don't want to modify the entire file but only a specific part. The syntax is:

:10,20s/oldword/newword/g

For example, to replace all occurrences of test with exam between lines 10 and 20, run:

:10,20s/test/exam/g

Search in Multiple Files

Searching for matching patterns across files is useful when working on large codebases or searching through logs spread across multiple files. It allows users to quickly locate and analyze relevant information.

Use the syntax below to search for a pattern in multiple files:

:vimgrep /phoenixNAP/ **/*.txt

This command searches for phoenixNAP in all .txt files in the current directory and subdirectories. After running the command, open the quickfix list to navigate through the results:

:copen
Checking the results in quickfix in Vim.

Use Enter to jump to a specific result in the list.

Conclusion

This article showed the basic and advanced search commands for Vi/Vim. The powerful text editor provides multiple options to search and find words and patterns or even execute shell commands directly from the editor.

Once you find the searched term, see how to cut, copy, or paste text in Vim.

Từ khóa » Vi In Linux Search