2/1/10

Grep for Binary Files (Script)

Example 10-7. A grep replacement for binary files

   1 #!/bin/bash
   2 # bin-grep.sh: Locates matching strings in a binary file.
   3
   4 # A "grep" replacement for binary files.
   5 # Similar effect to "grep -a"
   6
   7 E_BADARGS=65
   8 E_NOFILE=66
   9
  10 if [ $# -ne 2 ]
  11 then
  12   echo "Usage: `basename $0` string filename"
  13   exit $E_BADARGS
  14 fi
  15
  16 if [ ! -f "$2" ]
  17 then
  18   echo "File \"$2\" does not exist."
  19   exit $E_NOFILE
  20 fi 
  21
  22
  23 for word in $( strings "$2" | grep "$1" )
  24 # The "strings" command lists strings in binary files.
  25 # Output then piped to "grep", which tests for desired string.
  26 do
  27   echo $word
  28 done
  29
  30 # As S.C. points out, the above for-loop could be replaced with the simpler
  31 #    strings "$2" | grep "$1" | tr -s "$IFS" '[\n*]'
  32
  33
  34 # Try something like  "./bin-grep.sh mem /bin/ls"  to exercise this script.
  35
  36 exit 0

No comments:

Quick HTTP to HTTPS - Apache2

There are several methods for redirecting your Apache-based website visitors who might type your servers URL using the plain (non-secure) HT...