| 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` search_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 | IFS=$'\012' # Per suggestion of Anton Filippov. |
| 24 | # was: IFS="\n" |
| 25 | for word in $( strings "$2" | grep "$1" ) |
| 26 | # The "strings" command lists strings in binary files. |
| 27 | # Output then piped to "grep", which tests for desired string. |
| 28 | do |
| 29 | echo $word |
| 30 | done |
| 31 | |
| 32 | # As S.C. points out, lines 23 - 30 could be replaced with the simpler |
| 33 | # strings "$2" | grep "$1" | tr -s "$IFS" '[\n*]' |
| 34 | |
| 35 | |
| 36 | # Try something like "./bin-grep.sh mem /bin/ls" |
| 37 | #+ to exercise this script. |
| 38 | |
| 39 | exit 0 |