Saturday, December 20, 2014

Hex editing in Linux text console using Vim

I don't usually edits binary files. But when there is a need of binary editing, a capable tool is a must-have. In the past I used hexedit in the Linux text console. But yesterday I can't seem to find the correct package to install in one of CentOS servers. To my surprise, Vim is perfectly capable of doing hex editing, if only you know the secret.

VIM binary mode

Do you know that, Vim, our reliable text editor, have a binary mode option ?

vim -b filename

If we don't enable binary mode, some EOL (end of line) characters will get converted to other form. Binary corruption is possible if vim is still in text mode.

Convert to hex dump

use this command to change the file into its hex dump:


Edit the file

Edit the hex part of the file. The ascii part in the right side will not get converted back to binary, so stick to the left and middle column of the screen. 

Convert back to binary

This command will convert the hex dump to binary :

 :%!xxd -r

Afterwards you can write the file back 


Caveats : backup before you edit something. Binary file editing is an error-prone procedure.

No comments: