vi Find & Replace

find_and_replace1600

Syntax

screen-shot-2016-10-20-at-12-48-14-am

Range

  • [%]
    • All lines in the file.
  • [1,30]
    • line 1 to 30
  • [5,$]
    • line 5 to last line

Pattern

  • This can be plain text and also regular expression. Combining regular expression and this command, replacing words in vi, will be powerful.
  • \<pattern\>
    • This will get the exact match, not all contained word.
This is his bag

: %s/his/her/g
=> Ther is her bag

Above command changes This also because it contains “his”.

This is his bag

: %s/\<his\>/her/g
=> This is her bag

 

Flags

  • [C]
    • Confirm each substitution
  • [g]
    • Replace all occurrence in the line
    • If you don’t put, default is just replacing first occurrence.
  • [i]
    • Ignore case for the pattern

Count

  • Do substitution in N lines from the current position of the cursor
 :s/hi/hello/g 4 

This means change all hi to hello in 4 lines from current line.

 

Leave A Comment

Your email address will not be published. Required fields are marked *