The basics, for quick reference.
Search
- /
- Search the file downwards for the string specified after the /
- ?
- Search the file upwards for the string specified after the?
- n
- Repeat last search given by ‘/’ or ‘?’
- N
- Repeat the last search given by ‘/’ or ‘?’, except in the reverse direction
- F
- Search the current line backwards for the character specified after the ‘F’ command. If found, move the cursor to the position
- f
- Search the current line for the character specified after the ‘f’ command. If found, move the cursor to the position
- ;
- Repeat the last f or F
Replace
[address] s [/pattern/replacement/] [options] [count]
Address can be empty (current line only), or a range designated as follows:
| Symbol | Meaning |
|---|---|
| 1,$ | All lines in the file |
| % | All lines; same as 1,$ |
| x,y | Lines x through y |
| x;y | Lines x through y, with current line reset to x |
| 0 | Top of file |
| . | Current line |
| n | Absolute line number n |
| $ | Last line |
| x-n | n lines before x |
| x+n | n lines after x |
| -[n] | One or n lines previous |
| +[n] | One or n lines ahead |
| 'x | Line marked with x |
| '' | Previous mark |
| /pattern/ | Forward to line matching pattern |
| ?pattern? | Backward to line matching pattern |
Options
c Prompt for confirmation before each change
g Substitute all instances of pattern on each line
p Print the last line on which a substitution was made
i Ignore case for the search pattern
Examples:
:s/foo/bar/g
Replace every occurrence of the word foo with bar on current line.
:%s/foo/bar/c
For each line on the file, replace the first occurrence of foo with bar and confirm every substitution.
:1,10s/yes/no/g
Substitute on first 10 lines.
:%s/[Hh]ello/Hi/gc
Confirm global substitutions.
:%s/foo/bar/gi
Ignore the case of the pattern you want to substitute. This replaces foo, FOO, Foo, and so on.
:s/Fortran/\U&/ 3
Uppercase first instance of “Fortran” on next three lines.
:g/^[0-9][0-9]*/s//Line &:/
For every line beginning with one or more digits, add the “Line” and a colon.