Vi

  • built-in command line text editor for Mac and Linux
  • search and replace
    // global replace
    :%s/old-text/new-text/g
    // global replace interactively and case insensitive
    :%s/old-text/new-text/gci
    // global replace limit to 6 occure
    :%s/old-text/new-text/g 6
    // replace all with 10-15 lines
    :10,15s/finder/replacer/g
    // live select replace
    // ctrl-v to set line range then :s/ /g
    
    // replace whole word only
    :%s/\<is\>/was/g
    
    // replace similar whole word
    :%s/\<\(good\|nice\)\>/awesome/g
    
    // replace wildchar pattern, ball01 ball02
    :%s/ball..//g
    
    // express
    \=
    !_\ is the same
    ^ start end $
  • delete/cut range
    :n,md
    Deletes lines n through m
  • delete line containts
    // delete lines contains keyword
    :g/keyword
    :g/keyword/d
    
    // delete blank lines
    :g/^\s*$/d
    
    // delete all line NOT with pattern, not start with "
    :g!/^\s*"/d
    :v/^\s*"/d
    
    // delete all line NOT with pattern, contains cat or dog or pig
    :v/cat\|dog\|pig/d
  • paste
    P

2 modes

  • Switch to normal mode: <ESC>
  • Switch to edit mode: i or a

Quit

  • Exit Vi: :q
  • Exit Vi (ignore changes): :q!
  • Save: :w
  • Save and Exit: :wq
  • Switch to (edit) an other file: :edit FILENAME
navigation esc; then shortcut
cursor place h (left) j (down) k (up) l (right)
line start/end home / end
go to line 78 :78
display cmd
show line number :set number
off line number :set nu!
hex mode :%!xxd
exit hex %!xxd -r
function cmd
replace char r
delete char/line x / dd
paste shift+p
find :/wordToFind
find next/previous n / N
replace once on current line :s/OLD/NEW
replace all on current line :s/OLD/NEW/g
replace all in range line :#,#s/OLD/NEW/g (. for current line, $ for end line, 78 for line 78)
replace all in file :%s/OLD/NEW/g

cheat sheet