If a file stores data in contiguous bytes format, a program trying to read this file will need to be instructed on how to read it since such files do not directly define a compatible method for reading their associated content.
This type of file is called a binary file. Opening such a file on a normal text editor program will only display unreadable characters. It is because binary data store data as bytes and not as textual characters.
The headers of a binary file are accompanied by an instruction set that reveals how its stored data should be read. Since binary files can store any data type, we can broadly classify all file types as either binary or text.
Create Binary File in Linux
We are going to create a sample binary file that we will try to edit. We will first create a text file with some data in it and then convert the text file to a binary file using the hexdump command.
$ echo "LinuxShellTips changed my Linux perspective!" > simple.txt $ hexdump simple.txt > simple.bin
The cat command should confirm to us that the binary conversion was a success.
$ cat simple.bin
Editing Binary Files in Linux
We are going to use the xxd command associated with the vim editor package. We first need to open the file on Vim editor using the -b
flag since we are dealing with a binary file.
$ vim -b simple.bin
Use keyboard key [i]
to enter insert mode and edit the binary file where needed. For instance, we can remove the first-line hex entries 694c to see what happens.
Convert Binary File to Text in Linux
To convert the binary file to text mode to view the implemented changes, we will switch to command mode using the keyboard key [Esc]
and then key in the vim command:
:%!xxd -r
Once we hit [Enter]
on the keyboard, we should see the edits we made.
To save changes and quit vim use:
:wq
We have successfully demonstrated the possibility of editing a binary file in Linux using vim editor. Know of other cool ways of editing binary files? Feel free to leave a comment or feedback.