Created
May 11, 2012 16:06
-
-
Save putnamhill/2660663 to your computer and use it in GitHub Desktop.
binary grep
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
usage() { | |
cat <<EOT | |
Usage: ${0##*/} [-l] [-h] pattern [arg2] ... | |
Prints lines containing a BRE pattern, after stripping binary data. | |
Sort of like strings command followed by grep, only better. | |
If no file paths are specified after the pattern, paths are | |
read from stdin (tip: feed with find). | |
Options: | |
-l only list file(s) that contains the pattern | |
-h Display this message. | |
EOT | |
} | |
bgrep() { | |
if ( env LC_ALL=en_US.US-ASCII LANG=en_US.US-ASCII tr -cs '[:print:]' '\n' < "$1" | \ | |
# delete blank lines | |
sed '/^[[:blank:]]*$/d' | \ | |
# look for our pattern | |
grep $LIST_OPTS $PATTERN ); then | |
[ -z "$LIST_OPTS" ] && echo -ne "\tfound in: " | |
echo "$1" | |
fi | |
} | |
LIST_OPTS='' | |
# Parse the command-line options: | |
while getopts 'lh' option; do | |
case "$option" in | |
l) LIST_OPTS='-lq' ;; # list file(s) that contain pattern | |
h) usage; exit 0 ;; # Help. | |
?) usage; exit 0 ;; # illegal option: display usage | |
esac | |
done | |
(( OPTIND-- )) | |
shift $OPTIND | |
if [ $# -gt 0 ]; then # process remaining args on the commandline | |
PATTERN=$1 | |
shift | |
if [ $# -gt 0 ]; then # process remaining args on the commandline | |
while [ $# -gt 0 ]; do | |
path=$1 | |
shift | |
bgrep "$path" | |
done | |
else # read from stdin | |
while read path; do | |
bgrep "$path" | |
done | |
fi | |
else | |
echo 'Please enter a pattern to search for.' | |
usage | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment