grep binary file in linux

Linux Grep Binary Files for Strings

Generally, people use grep command to search for a string in files and folders. But grep command works only if your files & folders contains characters, numbers & symbols. How do you search for a character or string in a binary file? In this article, we will learn how to grep binary files for strings.


Linux Grep Binary Files for Strings

You can easily search binary files for strings using a combination of strings and grep command. The strings command returns all readable string texts in the file and removes any binary code or unreadable characters in it. It also works with streams and bytes, not just files. It is piped to grep command which is used to search for the required text. Here is the syntax of strings command.

$ strings /path/to/binaryfile | grep text_to_be_searched

For example, if you want to search for string ‘hello’ in a binary file data.txt, then here is the command for it.

$ strings data.txt | grep "hello"

Of course, strings command provides many options such as setting minimum string length, including whitespace, printing string offset, etc.

In this article, we have learnt how to grep binary files for strings. Basically, binary files contain mostly characters that are not human readable and many can not even be displayed on terminal. This is because not all characters & symbols used to represent binary values correspond to alphanumeric characters. So you cannot use cat or less command to view every binary file’s content. You may end up with a hung terminal window. Similarly, if you use grep command on a binary file, it may be unable to find the required string or give you an error. In such cases, it is very useful to pass the binary file through commands like strings which extracts readable characters from it, and then pass this output through commands like grep that are used to search for strings in files & folders.

Also read:

Linux Prevent File From Being Modified
Linux Rename File with Special Characters
Linux Rename File Starting With Dash
How to Disable Shutdown & Reboot Commands in Linux
How to Convert Files to UTF8 Encoding in Linux

Leave a Reply

Your email address will not be published. Required fields are marked *