Vim как найти слово

В этой статье описывается, как выполнять поисковые операции в Vim / Vi.

Vim или его предшественник Vi предустановлен в macOS и большинстве дистрибутивов Linux. Поиск текста — одна из самых распространенных задач при работе с файлами. Знание основ Vim может быть очень полезным, когда вы сталкиваетесь с ситуацией, когда ваш любимый редактор недоступен.

Базовый поиск

Для поиска в Vim вы должны быть в обычном режиме. Когда вы запускаете редактор Vim, вы находитесь в этом режиме. Чтобы вернуться в нормальный режим из любого другого режима, просто нажмите клавишу Esc.

Vim позволяет быстро находить текст с помощью / (косая черта) и ? (знак вопроса) команды.

Для поиска вперед нажмите / а для поиска назад нажмите ? , введите шаблон поиска и нажмите Enter чтобы запустить поиск:

Важно отметить, что команда поиска ищет шаблон как строку, а не целое слово. Если, например, вы искали «gnu», поиск совпадет с тем, что «gnu» встроено в слова большего размера, такие как «cygnus» или «magnum».

Нажмите n для поиска следующего вхождения или N в верхнем регистре для поиска в обратном направлении.

Основные шаги для выполнения поиска в Vim следующие:

  1. Нажмите / .
  2. Введите шаблон поиска.
  3. Нажмите Enter чтобы выполнить поиск.
  4. Нажмите n чтобы найти следующее вхождение, или N чтобы найти предыдущее вхождение.

Искать слово целиком

Для поиска всего слова начните поиск, нажав / или ? , введите < чтобы отметить начало слова, введите шаблон поиска, введите > чтобы отметить конец слова, и нажмите Enter чтобы выполнить поиск.

Например, для поиска «gnu» вы должны использовать /<work> :

Искать в текущем слове

Вы также можете выполнить поиск целого слова, переместив курсор на слово и нажав * (звездочка) для поиска вперед или # (решетка) для поиска в обратном направлении. Чтобы найти следующее совпадение, снова нажмите * или # .

История поиска

Vim отслеживает все операции поиска, выполненные вами в текущем сеансе. Чтобы просмотреть историю поиска, нажмите / или ? и используйте клавиши со стрелками вверх / вниз, чтобы найти предыдущую операцию поиска. Чтобы запустить поиск, просто нажмите Enter . Вы также можете отредактировать шаблон поиска перед выполнением операции.

Чувствительность к регистру

По умолчанию в результатах поиска учитывается регистр; поиск «GNU» не будет соответствовать «Gnu».

Чтобы игнорировать регистр :set ignorecase или :set ic в командной строке Vim. Вы также можете установить регистр игнорирования как вариант по умолчанию, добавив команду в ваш файл ~/.vimrc .

Чтобы вернуться в режим совпадения регистра, введите :set noignorecase или :set noic .

Другой способ принудительно игнорировать регистр — добавить c после шаблона поиска. Например, /Linuxc выполняет поиск без учета регистра. Верхний регистр C после шаблона приводит к поиску совпадения по регистру.

Выводы

Для поиска в Vim / Vi введите / или ? , введите шаблон поиска и нажмите Enter .

Не стесняйтесь оставлять комментарии, если у вас есть вопросы.

В этой статье описывается, как выполнять поисковые операции в Vim / Vi.

Vim или его предшественник Vi предустановлен на MacOS и большинстве дистрибутивов Linux. Поиск текста — одна из самых распространенных задач при работе с файлами. Знание основ Vim может быть очень полезно, когда вы сталкиваетесь с ситуацией, когда ваш любимый редактор недоступен.

Базовый поиск

Для поиска в Vim вы должны быть в обычном режиме. Когда вы запускаете редактор Vim, вы находитесь в этом режиме. Чтобы вернуться в обычный режим из любого другого режима, просто нажмите клавишу Esc.

Vim позволяет быстро находить текст с помощью команд /(косая черта) и ?(знак вопроса).

Для поиска вперед нажмите / и для поиска назад нажмите ?, введите шаблон поиска и нажмите Enter, чтобы запустить поиск:

Как искать в Vim/Vi

Важно отметить, что команда поиска ищет шаблон как строку, а не как целое слово. Если, например, вы искали «gnu», то поиск найдет совпадения, где «gnu» встроен в более крупные слова, такие как «cygnus» или «magnum».

Нажмите n для поиска следующего вхождения или заглавную букву N для поиска в обратном направлении.

Основные действия по поиску в Vim:

  1. Нажмите /.
  2. Введите шаблон поиска.
  3. Нажмите Enter, чтобы выполнить поиск.
  4. Нажмите n, чтобы найти следующее вхождение или N чтобы найти предыдущее вхождение.

Поиск всего слова

Чтобы выполнить поиск по всему слову, начните поиск, нажав / или ?, введите <, чтобы отметить начало слова, введите шаблон поиска, введите >, чтобы отметить конец слова, и нажмите Enter, чтобы выполнить поиск.

Например, для поиска «gnu» вы должны использовать /<work>:

Как искать в Vim/Vi

Поиск в текущем слове

Вы также можете выполнить поиск по всему слову, переместив курсор на слово и нажав *(звездочку) для поиска вперед или #(хэш) для поиска назад. Чтобы найти следующее совпадение, нажмите * или # еще раз.

История поиска

Vim отслеживает все операции поиска, которые вы сделали в текущем сеансе. Для просмотра истории поиска нажмите / или ? и используйте клавиши со стрелками вверх/вниз, чтобы найти предыдущую операцию поиска. Чтобы запустить поиск, просто нажмите Enter. Вы также можете отредактировать шаблон поиска перед выполнением операции.

Чувствительность к регистру

По умолчанию результаты поиска чувствительны к регистру; поиск «GNU» не будет совпадать с «Gnu».

Чтобы игнорировать регистр, введите :set ignorecase или :set ic в командной строке Vim. Вы также можете установить регистр игнорирования в качестве опции по умолчанию, добавив команду в свой файл ~/.vimrc.

Чтобы вернуться в режим соответствия регистра, введите :set noignorecase или :set noic.

Другой способ принудительно игнорировать регистр — добавить c после шаблона поиска. Например, /Linuxc будет выполнять поиск без учета регистра. Прописная буква C после шаблона вынуждают искать совпадения с регистром.

Вывод

Для поиска в Vim / Vi введите / или ?, введите шаблон поиска и нажмите Enter.

Не стесняйтесь оставлять комментарии, если у вас есть какие-либо вопросы.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

vi (visual editor) – лучший редактор текстовых файлов командной строки для Unix-подобных операционных систем.

Vim – это улучшенная версия текстового редактора vi, используемого в современных системах.

Это текстовый редактор с широкими возможностями настройки.

Это руководство поможет вам найти текст, строку или шаблон в текстовом редакторе Vi (m).

Как искать в редакторе Vi (m)

Чтобы начать поиск в редакторе Vi (m), сначала нажмите клавишу ESC, чтобы переключиться в командный режим в редакторе.

Затем нажмите «/», а затем введите текст, который нужно найти.

  • Нажмите ESC
  • Ведите  “/”
  • Ведите шаблон поиска
  • Нажмите клавишу Enter или Return для поиска.
/pattern

Система переместит курсор к первому совпадению искомой строки.

Затем используйте сочетания клавиш для перехода к предыдущей или следующей строке поиска, как показано ниже:

  • Нажмите n (строчная буква) для поиска следующих вхождений
  • Нажмите N (заглавной буквой), чтобы найти предыдущие вхождения

Поиск без учета регистра в Vim

По умолчанию vim ищет совпадения с учетом регистра.

Чтобы искать шаблон во всех случаях, вам нужно отключить регистр с помощью команды set в vim.

Введите следующую команду в vim, чтобы отключить поиск с учетом регистра.

This tip shows how to search using Vim, including use of * (the super star) to search for the current word. Search options are described, and the see also section links to other useful searching tips.

Basic searching[]

In normal mode you can search forwards by pressing / (or <kDivide>) then typing your search pattern. Press Esc to cancel or press Enter to perform the search. Then press n to search forwards for the next occurrence, or N to search backwards. Type ggn to jump to the first match, or GN to jump to the last.

Note: ggn skips first match if it is at row 1 column 1. Type Gn to jump to the real first match. For this, 'wrapscan' must be on (default).

Search backwards by pressing ? then typing your search pattern. Pressing n searches in the same direction (backwards), while N searches in the opposite direction (forwards).

Searching for the current word[]

In normal mode, move the cursor to any word. Press * to search forwards for the next occurrence of that word, or press # to search backwards.

Using * (also <kMultiply>, <S-LeftMouse>) or # (also <S-RightMouse>) searches for the exact word at the cursor (searching for rain would not find rainbow).

Use g* or g# if you don’t want to search for the exact word.

Using the mouse[]

With appropriate settings, you can search for an exact word using the mouse: Shift-LeftClick a word to search forwards, or Shift-RightClick to search backwards.

This needs a GUI version of Vim (gvim), or a console Vim that accepts a mouse. You may need the following line in your vimrc to enable mouse searches:

:set mousemodel=extend

In gvim, click the Edit menu, then Global Settings, then the «tear off» bar at the top. That will show a floating Global Settings menu with useful Toggle Pattern Highlight and Toggle Ignore-case commands.

More searching[]

Vim maintains a search history. Type / or ? and use the arrow up/down keys to recall previous search patterns. You can edit a pattern, and press Enter to search for something different.

Suppose the cursor is on a word, and you want to search for a similar word.

Press / then Ctrl-r then Ctrl-w to copy the current word to the command line. You can now edit the search pattern and press Enter. Use Ctrl-r Ctrl-w for a <cword>, or Ctrl-r Ctrl-a for a <cWORD>.

After searching, press Ctrl-o to jump back to your previous position (then Ctrl-i will jump forwards).

After searching, an empty search pattern will repeat the last search. This works with /, :s and :g.

So, after searching for a word, use :%s//new/g to change all occurrences to ‘new’, or :g/ to list all lines containing the word. See substitute last search.

You can enter a count before a search. For example 3/pattern will search for the third occurrence of pattern, and 3* will search for the third occurrence of the current word.

You can highlight all search matches (and quickly turn highlighting off), and you can use a mapping to highlight all occurrences of the current word without moving (see highlight matches).

A search can include an offset to position the cursor. For example, searching with /green positions the cursor at the beginning of the next «green», while /green/e positions the cursor at the end of the next «green». :help search-offset

A search pattern can include characters with codes specified in decimal or hex. For example, searching with /%d65 or with /%x41 both find ‘A‘ (character decimal 65 = hex 41), and searching with /%d8211 or with /%u2013 both find ‘‘ (a Unicode en dash). :help /%d

Case sensitivity[]

By default, searching is case sensitive (searching for «the» will not find «The»).

With the following in your vimrc (or entered via a toggle mapping), searching is not case sensitive:

:set ignorecase

Now the command /the will find «the» or «The» or «THE» etc. You can use c to force a pattern to be case insensitive, or C to force a pattern to be case sensitive. For example, the search /thec is always case insensitive, and /theC is always case sensitive, regardless of the 'ignorecase' option.

If 'ignorecase' is on, you may also want:

:set smartcase

When 'ignorecase' and 'smartcase' are both on, if a pattern contains an uppercase letter, it is case sensitive, otherwise, it is not. For example, /The would find only «The», while /the would find «the» or «The» etc.

The 'smartcase' option only applies to search patterns that you type; it does not apply to * or # or gd. If you press * to search for a word, you can make 'smartcase' apply by pressing / then up arrow then Enter (to repeat the search from history).

When programming, there is generally no reason to want 'smartcase' to apply when you press *. For other situations, use:

:nnoremap * /<<C-R>=expand('<cword>')<CR>><CR>
:nnoremap # ?<<C-R>=expand('<cword>')<CR>><CR>

With these mappings, if 'smartcase' is on and you press * while on the word «The», you will only find «The» (case sensitive), but if you press * while on the word «the», the search will not be case sensitive.

The mapping for * uses / to start a search; the pattern begins with < and ends with > so only whole words are found; <C-R>= inserts the expression register to evaluate expand('<cword>') which inserts the current word (similar to Ctrl-R Ctrl-W but avoiding an error when used on a blank line).

Show the next match while entering a search[]

To move the cursor to the matched string, while typing the search pattern, set the following option in your vimrc:

:set incsearch

Complete the search by pressing Enter, or cancel by pressing Esc. When typing the search pattern, press Ctrl-L (:help c_CTRL-L) to insert the next character from the match or press Ctrl-R Ctrl-W (:help c_CTRL-R_CTRL-F) to complete the current matching word.

Other search options[]

By default, the 'wrapscan' option is on, which means that when «search next» reaches end of file, it wraps around to the beginning, and when «search previous» reaches the beginning, it wraps around to the end.

These examples show how to set 'wrapscan' (abbreviated as 'ws'):

:set nowrapscan        " do not wrap around
:set wrapscan          " wrap around
:set wrapscan!         " toggle wrap around on/off
:set ws! ws?           " toggle and show value

By default, search hits may occur in lines at the top or bottom of the window. The 'scrolloff' option controls whether context lines will be visible above and below the line containing the search hit.

If your text is folded, you probably want folds to automatically open to reveal search hits. To achieve that, the 'foldopen' option should include «search» (check by entering :set fdo?). :help ‘foldopen’ Conversely, this option can be used to Search only in unfolded text.

See also[]

Searching
  • Highlighting search matches
  • Search for visually selected text
  • Search patterns regex tutorial with useful searches
  • Search for current word in new window
  • Make search results appear in the middle of the screen
  • Search and replace using :s to substitute text
  • Browse the searching category for more.
Searching in multiple files
  • Find in files within Vim
Finding a file from its name
  • Project browsing using find
  • Find files in subdirectories

References[]

  • :help *
  • :help <S-LeftMouse>
  • :help :<cword>
  • :help jump-motions
  • :help ‘iskeyword’ controls which characters * considers make a word

[]

On UK keyboards, <Shift-3> produces ₤ but works just like # for searching backwards.

I can search word in vim with /word. How can I search only for word, excluding searches for word1 and word2?

Freedom_Ben's user avatar

Freedom_Ben

11k10 gold badges68 silver badges88 bronze badges

asked Jan 19, 2009 at 19:49

kal's user avatar

1

like this:

/<word>

< means beginning of a word, and > means the end of a word,

Adding @Roe’s comment:
VIM provides a shortcut for this. If you already have word on screen and you want to find other instances of it, you can put the cursor on the word and press '*' to search forward in the file or '#' to search backwards.

answered Jan 19, 2009 at 19:51

Nathan Fellman's user avatar

Nathan FellmanNathan Fellman

122k100 gold badges258 silver badges319 bronze badges

8

  1. vim filename
  2. press /
  3. type word which you want to search
  4. press Enter

answered Dec 14, 2015 at 10:01

Mushir's user avatar

MushirMushir

1,2239 silver badges12 bronze badges

3

If you are working in Ubuntu,follow the steps:

  1. Press / and type word to search
  2. To search in forward press ‘SHIFT’ key with * key
  3. To search in backward press ‘SHIFT’ key with # key

SOFe's user avatar

SOFe

7,8294 gold badges32 silver badges60 bronze badges

answered Aug 11, 2016 at 7:11

Priya R's user avatar

Priya RPriya R

4834 silver badges2 bronze badges

4

For basic searching:

  • /pattern — search forward for pattern
  • ?pattern — search backward
  • n — repeat forward search
  • N — repeat backward

Some variables you might want to set:

  • :set ignorecase — case insensitive
  • :set smartcase — use case if any caps used
  • :set incsearch — show match as search

answered Jan 5, 2018 at 11:36

NeeruKSingh's user avatar

NeeruKSinghNeeruKSingh

1,5453 gold badges21 silver badges26 bronze badges

1

Basic search (once you have opened the file in vim) using vim:

-Hit ESC on your computer keyboard

-Hit the forward slash symbol on your keyboard /

-Type the word or symbol you intend to search; for example, to search for the term «rbmq» type /rbmq

-Hit Enter

-Hit n to search forward (moving towards the end of the file) and N to search backward (moving towards the beginning of the file)

answered Jul 22, 2021 at 19:10

Asif's user avatar

AsifAsif

6541 gold badge7 silver badges14 bronze badges

1

Понравилась статья? Поделить с друзьями:
  • Как найти русскую девушку в сша
  • Как составить свой индекс здоровья
  • Как старик нашел медведя
  • Как найти валентность оксида меди
  • Как найти своего клона по фото бесплатно