Vim (vi) – multiline search replace with confirmation

Vi (or Vim) is a very powerful and light weight editor which is available on any Linux or Mac. Even if you are working on production environment remotely, very likely vi will be available there. For casual simple editing also it works nicely.

Searching/replacing on multiple lines is a very common use case. Here are some approaches to do multiline search replace with confirmation in vi:

Vi – searching and replacing from current line till last line

  1. Once you hit escape the enter the following command for searching and replacing text from current line till last line:
    Dissecting above command
    String Purpose
    . Current line
    $ last line in file
    .,$ Lines range
    s To search replace
    Line String to be replaced
    Row Replacement string
    Flag g global in a line
    Flag c Confirm before replacing

    Here is a sample file opened in vi with above command used:

  2. After entering the above hit enter. If everything is correct, vi will stop at first match and ask for confirmation as shown below. Press y or n as desired.
  3. Once all replacements are done, you will see a summary as shown below:

Vi – more search replace scenarios

  1. Use 1,$ or % to search/replace from first line till last line.
  2. Use .,+9 to search/replace in 10 lines starting from current line
  3. Skip flag c to replace without confirmation
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments