Q. I’ve just installed CentOS Linux server and started to use vi text editor to make changes to config files. How do I perform search and replace operation using vi / vim text editor?
A. vi (vim) is not difficult to learn, the vi editor is well known and used for both writing code and editing config files.
VI search and replace command format
Simple format is as follows:
VI search and replace command examples
Let us say you would like to find a word called “foo” and replace with “bar”.
First hit [Esc] key
Type : (colon) followed by %s/foo/bar/ and hit [Enter] key.
Above command will replace first occurrence of word foo with bar on all lines. The % is shorthand for all lines.
To replace all occurrences of word foo with bar on all lines, use the g option (which indicates all occurrences on a line).
Note that the g can be replaced with a number 1,2,…N to change only the n’th occurrence on each line.
Use find and replace on line ranges (match by line numbers)
You can also make changes on range of lines i.e. replace first occurrence of foo with bar on lines 5 through 20 only, enter:
Following command will replace first occurrence of foo with bar starting at the current line for the next 100 lines:
Match by words
Finally, you can match by words i.e. replace first occurrence of foo with bar starting at at the next line containing a word “test”:
As usual you can specify ranges:
Please note that all search/replace commands should be start with the [ESC]: keystroke combination only.
🐧 19 comments so far... add one ↓
|Category||List of Unix and Linux commands|
|Disk space analyzers||df • duf • ncdu • pydf|
|File Management||cat • cp • mkdir • tree|
|Firewall||Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04|
|Modern utilities||bat • exa|
|Network Utilities||NetHogs • dig • host • ip • nmap|
|OpenVPN||CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04|
|Package Manager||apk • apt|
|Processes Management||bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop|
|Searching||ag • grep • whereis • which|
|User Information||groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w|
|WireGuard VPN||Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04|