October 7th, 2007 by bkoch
Any experienced *nix admin that is worth his salt knows vi, but more than ever there are users who will only use vi to plow through configuration and/or log files. That is who I am writing this post for.
Hopefully as a user of a *nix system you will know how to move the cursor, page up and down and edit and save the file. But what about searching for a string or doing a search and replace. These are the functions that are going to be most useful when going through config files or logs.
1. Search for text
You first hit Esc to get you out of editing or Insert mode.
Then type a forward slash (’/') and the string you are looking for.
/SomeText
When you hit Enter your cursor will be moved to the first occurrence of the string from where you cursor currently sits.
If you type n then your cursor will move the next occurrence of the string down the file.
You can move up file if you use a capital N, meaning hit Shift+N.
Pay attention because once you hit the top or the bottom of the file the search will wrap around to the other end of the file.
2. Replace text
This is another powerful tool with vi. You can search and replace text using regular expressions. I am not going into detail about this but will hit on the basics to whet your appetite.
Once again hit the Esc key to get you out of Insert mode.
Then type the following:
:%s/SomeText/YourNewText/
This will replace every occurence of SomeText with YourNextText in the file. You might find you need to include a g at the end to globally replace your text, like this:
:%s/SomeText/YourNewText/g
If you only want to replace the string on the line you are on then remove the %. So your expression will look like this:
:s/SomeText/YourNewText/
3. Removing ^M from DOS files.
Now I am sure many of you have gotten files that have the ^M characters after you have moved a file from a Windows computer to a *nix based computer. You could just use the utility dos2unix but not all systems will have it. So you can use vi to accomplish the task.
Get out of Insert mode then type the following:
:%s/^v^m//g
The ^ character is signifies the control key. What you will actually see is this:
%s/^M//g
This will strip out all of the ^M characters.
I hope you will find this information useful.