Tricks with vi: Hex Editing, Running sudo

I’ve been a faithful user of vi for many years, but I only recently learned these two useful tricks.

Trick 1: Hex Editing in vi

The first trick is switching vi to a sort of hex edit mode. To view the the contents of a (potentially binary) file in hexadecimal that you have already opened in vi, press ESC and then type “:%!xxd” (without the quotes). The contents of your vi session will now look like the output of the xxd hex dump tool:

0000000: 4c6f 7265 6d20 6970 7375 6d20 646f 6c6f Lorem ipsum dolo
0000010: 7220 7369 7420 616d 6574 2c20 636f 6e73 r sit amet, cons
0000020: 6563 7465 7475 7220 6164 6970 6973 6963 ectetur adipisic
0000030: 696e 6720 656c 6974 2c20 7365 6420 646f ing elit, sed do
0000040: 2065 6975 736d 6f64 2074 656d 706f 7220 eiusmod tempor
0000050: 696e 6369 6469 6475 6e74 2075 7420 6c61 incididunt ut la

I could now choose to (for example) choose to change the first character to a space by replacing the first byte, 4c, with 20:

0000000: 206f 7265 6d20 6970 7375 6d20 646f 6c6f Lorem ipsum dolo
0000010: 7220 7369 7420 616d 6574 2c20 636f 6e73 r sit amet, cons
0000020: 6563 7465 7475 7220 6164 6970 6973 6963 ectetur adipisic
0000030: 696e 6720 656c 6974 2c20 7365 6420 646f ing elit, sed do
0000040: 2065 6975 736d 6f64 2074 656d 706f 7220 eiusmod tempor
0000050: 696e 6369 6469 6475 6e74 2075 7420 6c61 incididunt ut la

Note that the text on the right is not automatically updated when you modify the hex. If you were to save the file at this point, it would be saved as it appears in the vi session (i.e. the contents of the file would look like the output of xxd). Revert back to the normal text edit mode with “:%!xxd -r”, and then save.

Trick 2: Running sudo Within vi to Edit a Read-Only File

There are many times when I open a file in vi and begin editing it without noticing the “Changing a readonly file” warning that appears. Then, after making numerous updates, I try to save my changes, only to get the “Can’t open file for writing” message… I forgot to run vi with sudo. One option is to exit vi without saving, run “sudo vi”, and then redo all my changes, which can be painful if there were a lot of updates. Another option: press ESC and then type “:w !sudo tee %”. Type your password, press ENTER when prompted to continue, and then press “L” to reload the now-modified file in the existing vi session. Your updates will have been written to disk. Note that you will need to follow this procedure every time you wish to write the file within that vi session.