Using Vim as a diff tool

Firstly I will start with why to not use diff. I am not suggesting a replacement, I have simply found that Vim offers a much better interface, that is available on most (*nix based) server environments for comparing and merging files side by side.

Getting started

vim -d file_original.txt file_new.txt

Your tool of choice here is vim -d, so if you like this as a ‘patch’ to diff, why not be naughty and alias it? I have aliased alias diff='vim -d' in my shell preferences.

Getting fancy

Wow, i can see the difference between 2 files, big deal! Try adding more files to the arguments, suddenly we have loads more power to compare multiple files, easily.

vim -d file_original.txt file_new.txt file_new_ammendments.txt

Commands

ctrl+ww - will let you navigate buffers.

When comparing just 2 files, these commands will be handy when you select the lines to merge

  • dp - diff put
  • do - diff obtain/get

If you are in multi diff mode, these may be handy as you need to write long hand commands;

  • :diffget 3 If you were in buffer 1, writing this command would obtain the difference in buffer 3
  • :diffpu 1 Again, write this in buffer 3 and it will place the change in buffer 1

Writing/saving changes
:wqall

Further Reading

Quick text replacement Vi tip

Vim logoThis came about as i wanted to replace just a few lines of text in vi.

Work out what range of lines to select

:set number

Find the lines you wish to modify

35 #Hosts per intl
36 192.168.0.22 uk.dev.site.com
37 192.168.0.22 de.dev.site.com
38 192.168.0.22 es.dev.site.com
39 192.168.1.92 it.dev.site.com
40 192.168.0.21 fr.dev.site.com

Do the replacement

:36,40s/patternToReplace/replacementText/gc

Tips

  • If your looking to do a lot of replacements, take out the ‘c’ at the end of the substitution (if your confident on what your changing), this is the confirmation option
  • If your unfamiliar with all the commands in vi, simply type ‘u’ (undo) if you mess up
  • Like the command line, vi has a history so type ‘:’ and use the up and down arrows to retrieve your previous text replacements
  • To turn line numbering off, type :set nonumber

A bit about Carbon Silk

Its a design/development centric site by James Broad, a London based web developer working at Yahoo!. I create compelling sites and applications for the web.

Categories

You may also like

Social Stuff

Email:
jb@carbonsilk.com
Linked In:
http://www.linkedin.com...
Twitter:
http://twitter.com/kulor
Del.icio.us:
http://del.icio.us/kulor