vi/vim question: How do I convert all occurrences of
XYZ in a file using the vi/vim editor?
Answer: This is actually easy to do with the vi or vim editor. Just go into "last line mode" by typing the ":" character, then enter a command like this to replace all occurrences of the string
ABC with the string
and then press [Enter]. This vi command replaces every occurrence of
XYZ on every line, and even when there are multiple occurrences on a line.
I thought of this because I recently needed to convert all tab characters in a file with two spaces (I was converting some Java code someone gave me to standards that I follow). To convert each tab in the file to two spaces, I used this command:
Note that in both of these examples the "g" character at the end of the command means "global". If you don't use this "g" the tab character will only be replaced the first time it is seen on a line, but if you add the "g" at the end of the command every tab character in each line will be replaced.