There are many instances when it’s useful to have multiple files open in vim, but if you aren’t familiar with this tool you can find yourself needlessly jumping around between multiple windows. If you are doing any type of real systems work on a Linux operating system I suggest that you familiarize yourself with vim. If you are not already using vim start by opening a command prompt and type vimtutor, once you’ve become familiar with how to navigate, search, and edit a document with vim this post will make more sense to you.
Use vim to see what is different between two files
There are several ways to find differences between two files on a Linux server or desktop. I like to use vim when I’m scanning a configuration file for recent changes from an earlier iteration ( assuming of course that there is a backup of the last known, good, configuration).
Comparing two files is a common task and there are several ways to view the differences between multiple files, but occasionally you may want to do this visually side by side.
Create two files file1 and file2.
file1 looks like this:
This is a file to test diff
Similarly file2 looks like this:
This is a file to test diff
With the “-d” option vim can open two, three, or four files and vim will open the files and highlight the line that is different. Try it.
vim -d file1 file2
You should see something similar to this:
Notice how the file opens with the cursor set to the line that is different, this is so that you can quickly get to work at the exact place where the files differ. Also helpful, is the fact that vim will automatically highlight the entire line to quickly draw your attention to the differences.
Using -d highlights a use for the split command. If you are working on a file and want to look at another file at the same time. Maybe to use some lines as a template, or just to compare an old configuration to a new one you can use the :split or :vsplit command.
Open file1 in vim
And then issue the split command to open file2
The default split command will split the screen horizontally:
Close file2 and this time look at the vertical split by issuing the vsplit or vsp command
This time, as the name suggests, the window will split horizontally allowing you to view files side by side. Personally I find this format to be the more useful of the two.
You can navigate between each split by using the key combination ctrl-w and then the direction key in which you want to move. So, to move from file2 to file1 you would hit ctrl w and then the right arrow (or the L key if you don’t like moving your hand quite so far).
There are other fancy things you can do with files in vim. If you are feeling a little wild look up tabs and buffers, both of which might make your life a little easier if you aren’t already using them.