junk food for the brain …
Posts tagged vim
Stop Vim from Highlighting Search Results
Jul 14th
You can search to words in vim using the ‘/’ key when you’re in command mode. Unfortunately, new admins in their desperation to find a word may inadvertently specify a term too generic.
Vim provides search highlighting, but sometimes, the results are just plain fugly. For example, when searching for the word module in a httpd.conf file, this is what could happen:
Yeah, not really the the most visually pleasing. To temporarily turn of highlighting, just type
:nohlsearch
in vim command mode.
The next time you search for something, or press the ‘n’ key, it will be automatically turned back on.
How to search and replace in Vim
Jun 25th
Just for reference, may help other people. Searching for text and replacing in vim is an invaluable skill, which helps sysadmins during the conf. file troubleshooting.
For example, assume you have this /etc/hosts file with a list of machines that are numbered sequentially. For some insane reason, some dude suggests a now naming scheme. Replacing 10 or 15 lines manually is a pain, not to mention error prone.
192.168.0.1 node01 192.168.0.2 node02 192.168.0.3 node03 192.168.0.4 node04 192.168.0.5 node05 192.168.0.6 node06
Now, your resident office genius decides that the names for these machines should be cluster-nodexx instead of nodexx. Great, now imagine having 200 machines in your hosts file. No way you’re going to manually edit that by hand. This is where vim’s search & replace function comes in handy.
First, open the file in vim:
# vim hosts
Now, to replace the the word node with cluster-node, press the colon “:” to enter command mode an type the following:-
:%s/node/cluster-node/gc
Lets break down the command.
- %s : instructs vim to search
- /node/: The words within the first two forward slashes are the characters vim will search for
- /cluster-node/: The words between the second and third forward slashes are what vim will replace node with.
- g: after the thrid forward slash, the ‘g’ stands for global. Without this, vim will only replace the first occurrence of the word node.
- c: ‘C’ will make vim prompt you for confirmation before replacing the word. Very handy especially when editing source or configuration files.
- Here’s an example of how this would look like:
Note the highlighted matches, and the prompt below asking for your confirmation.
This should help you do some mass replacing with ease.
