Posted: . At: 1:01 PM. This was 4 years ago. Post ID: 13982
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.



Sponsored



How to search a file with grep for certain hexadecimal values.


The grep utility is very useful for searching for files and text snippets. It can also be used to search a file for certain values in hexadecimal.

In the example below, I am searching for the text “JFIF” in hexadecimal in certain files. This will tell me that they are jpg image files.

The hexadecimal value 4a 46 49 46 is formatted like this for searching with grep. \x4a\x46\x49\x46.

4.4 Wed Jan 22 jason@Yog-Sothoth 0: $ grep -obUaP '\x4a\x46\x49\x46' *.*
0011225480_130.jpg:6:JFIF
0013530672_130.jpg:6:JFIF
1531698862207.jpg:6:JFIF
1531698862211.jpg:6:JFIF
1531698862213.jpg:6:JFIF
1531698862215.jpg:6:JFIF
1531698862217.jpg:6:JFIF
1531698862219.jpg:6:JFIF
1531698862221.jpg:6:JFIF
1531698862224.jpg:6:JFIF
1531698862225.jpg:6:JFIF
1531698862226.jpg:6:JFIF
1531698862227.jpg:6:JFIF
1531698862229.jpg:6:JFIF
1531698862231.jpg:6:JFIF

This returns all jpg files.

This example returns all png format files by looking for the PNG string in hexadecimal.

4.4 Wed Jan 22 jason@Yog-Sothoth 0: $ grep -obUaP '\x50\x4e\x47\x0d' *.*
1531699564904.png:1:PNG
1531699564908.png:1:PNG
1531699564910.png:1:PNG
1531699564913.png:1:PNG
1531699564915.png:1:PNG
1531699564917.png:1:PNG
1531699564918.png:1:PNG
1531699564920.png:1:PNG
1531699564921.png:1:PNG
1531699564923.png:1:PNG
1531699564924.png:1:PNG
1531699564927.png:1:PNG

Use this command to get the file header we are looking for as an example.

4.4 Wed Jan 22 jason@Yog-Sothoth 0: $ hexdump -C 1531699564927.png | head -n 1
00000000  89 50 4e 47 0d 0a 1a 0a  00 00 00 0d 49 48 44 52  |.PNG........IHDR|

Get the header data from a file this way.

4.4 Wed Jan 22 jason@Yog-Sothoth 0: $ file 1531699564920.png | awk '{print $2}' | hexdump -C
00000000  50 4e 47 0a                                       |PNG.|
00000004

This is a very unique way to get a listing of PNG or JPEG files with the Linux command line. Very interesting indeed.

This will find all ELF Linux binary executable files.

4.4 Wed Jan 22 jason@Yog-Sothoth 0: $ grep -obUaP '\x45\x4c\x46' *
archdetect:1:ELF
bash:1:ELF
blockdev-wipe:1:ELF
brltty:1:ELF
btrfs:1:ELF
btrfsck:1:ELF
btrfs-debug-tree:1:ELF
btrfs-find-root:1:ELF
btrfs-image:1:ELF
btrfs-map-logical:1:ELF
btrfs-select-super:1:ELF
btrfstune:1:ELF
btrfs-zero-log:1:ELF
bunzip2:1:ELF
busybox:1:ELF

The \x45\x4c\x46 string finds all ELF strings.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.