Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace only whole-word matches in Vim?

Tags:

regex

vim

Code sample:

for file in files:
  do_something(root+file)

I want to replace file with f but I must keep files.

Usually I use the below command:

:%s/file/f/gcI

but it matches files as well. Is there any way to match only a whole word which works for the (root+file) syntax too?

like image 358
guilin 桂林 Avatar asked Oct 02 '10 10:10

guilin 桂林


People also ask

How do I find and replace every incident of a text string in vim?

When you want to search for a string of text and replace it with another string of text, you can use the syntax :[range]s/search/replace/. The range is optional; if you just run :s/search/replace/, it will search only the current line and match only the first occurrence of a term.

How do I search a whole word in vim?

As soon as press 'w', you can type your word right away, and enter to perform a wholeword search.

How do I match a word in vim?

In normal mode, press / to start a search, then type the pattern ( \<i\> ), then press Enter. If you have an example of the word you want to find on screen, you do not need to enter a search pattern. Simply move the cursor anywhere within the word, then press * to search for the next occurrence of that whole word.

How do we search for old and replace it with new in vim?

To search in the current file, you just need to type / in normal mode. Then, you need to type your search pattern, press enter , and the result becomes highlighted in your file. To go backward and forward through the results, you can type n and N (for n ext) respectively. Using / will search forward in the file.


1 Answers

Use \< and \> to match the beginning and the end of a word:

:%s/\<file\>/f/gcI
like image 164
livibetter Avatar answered Oct 15 '22 12:10

livibetter