
The ECN No Name Newsletter is no longer being published. This is an archived issue.
[previous article] [next article]Have you ever wanted to compare the content of two files? Maybe you have really muffed-up an editing session and wished you could compare the current contents of the editor's buffer with the lastest disk version. Perhaps you have needed to compare the disk version of a file with a file recovered using the "vi-r filename" command. UNIX provides an easy way to do this by using the diff utility and some handy features of the vi/ex/edit editor.
The diff utility compares two files and lists the lines that are different. The command used to compare two files is "diff file1 file2". For more information type "help diff".
In the editor, ":w !command" can be used to send the buffer's file copy to the input of a command. For example, the editor command ":w !spell" would do a spell-check on the buffer file and print the misspelled words on your terminal. Be sure to put a space between the w and the ! or the file will be written to a file named spell instead of being sent to the "spell" program.
Typing ":w !diff - filename" combines "diff" with the editor's ":w!" command, providing a way to compare the buffer file with the latest disk version. This command tells the editor to take the current buffer copy (:w !) and process it through the diff command, taking - (standard input, in this case the buffer copy) and compare it to the disk file (filename). Use of another handy editor feature makes this comparison even easier. When using editor commands, the name of the file you are currently editing may be replaced with the character " % ". Making use of this, our command for comparing the editor's buffer file with the version on disk becomes ":w !diff - %". If you know there are many differences between files, it may be easier to read the results if you process the entire command through more; thus type ":w !diff - % | more" then you will be able to view the listing one screenful at a time.