ubuntu, updated
Vim: search and replace
Find text, jump between hits, and search and replace in vim, including in a selection and with confirmation.
Search
| What | Keys (normal mode) |
|---|---|
| Search forward | /word, then Enter |
| Search backward | ?word |
| Next / previous hit | n / N |
| Search the word under the cursor | * (forward), # (backward) |
| Case-insensitive, just this search | /word\c |
| Remove the highlighting | :noh |
| Go to line 120 | :120 |
Special characters (. * [ ] / \) must be escaped with a backslash: /192\.168\.1\.1.
Replace
The command is :s (substitute): :RANGE s/OLD/NEW/FLAGS.
| What | Command |
|---|---|
| First hit in the current line | :s/old/new/ |
| All hits in the current line | :s/old/new/g |
| All hits in the file | :%s/old/new/g |
| All hits, ask each time | :%s/old/new/gc (y yes, n no, a all, q quit) |
| Ignore case | :%s/old/new/gi |
| Only in lines 10 to 20 | :10,20s/old/new/g |
| Only in the selection | select with V, then :s/old/new/g (vim adds '<,'>) |
| Whole word only | :%s/\<old\>/new/g |
Paths contain slashes. Use another separator instead of escaping them all:
:%s#/var/www/old#/srv/www/new#g
Handy examples
| Task | Command |
|---|---|
| Delete all comment lines | :g/^#/d |
| Delete all empty lines | :g/^$/d |
| Delete lines containing “debug” | :g/debug/d |
| Keep only lines containing “error” | :v/error/d |
| Remove trailing spaces | :%s/\s\+$//e |
| Comment out lines 5 to 15 | :5,15s/^/# / |
| Uncomment them again | :5,15s/^# // |
| Replace tabs with 2 spaces | :%s/\t/ /g |
:g/PATTERN/COMMAND runs a command on every line that matches. :v does the opposite.
Search in many files
Inside vim you can search across files, but on a server it is faster to use grep and then open the hit:
grep -rn "listen 80" /etc/nginx/
vim +23 /etc/nginx/sites-enabled/default # open at the line grep showed