Skip to main content
Tweeted twitter.com/StackUnix/status/809959564305137664
edited tags
Link
Jeff Schaller
  • 68.8k
  • 35
  • 122
  • 267
Source Link
hugomg
  • 6.1k
  • 5
  • 43
  • 55

How can I count the number of times a byte sequence occurs in a file?

I want to count how many times a certain sequence of bytes happens inside a file that I have. For example, I want to find out how many times the number \0xdeadbeef occurs inside an executable file. Right now I am doing that using grep:

#/usr/bin/fish
grep -c \Xef\Xbe\Xad\Xde my_executable_file

(The bytes are written in reverse order because my CPU is little-endian)

However, I have two problems with my approach:

  • Those \Xnn escape sequences only work in the fish shell.
  • grep is actually counting the number of lines that contain my magic number. If the pattern occurs twice in the same line it will only count once.

Is there a way to fix these problems? How can I make this one liner run in Bash shell and accurately count number of times the pattern occurs inside the file?