Skip to content

Instantly share code, notes, and snippets.

@zachelko
Created January 31, 2014 17:31
Show Gist options
  • Save zachelko/8737819 to your computer and use it in GitHub Desktop.
Save zachelko/8737819 to your computer and use it in GitHub Desktop.
Recursively search for text in files based on file-extension from a given starting directory (defaults to cwd)
#!/bin/bash
#
# Sample usage:
# Find "QObject" in every .hpp / .cpp file located somewhere within /home/zach/coderoot
# dofind.sh "QObject" hs /home/zach/coderoot
#
# Same as above, but begin the search in the current directory, and only check .cpp files
# dofind.sh "QObject" s
#
# Same as above, but specify the file extension manually
# dofind.sh "QObject" *.cc /home/zach/coderoot
SEARCH_TEXT=$1
if [ "$2" = h ]; then
INCLUDE_PATTERN="*.hpp"
elif [ "$2" = "s" ]; then
INCLUDE_PATTERN="*.cpp"
elif [ "$2" = "hs" ] || [ "$2" = "sh" ]; then
INCLUDE_PATTERN="*.[hc]pp"
else
INCLUDE_PATTERN=$2
fi
# Use user-provided root directory
# or fall-back to the current directory
if [ ! -z "$3" ]; then
START_PATH=$3
else
START_PATH="."
fi
# echo $INCLUDE_PATTERN
# echo $SEARCH_TEXT
# echo $START_PATH
grep -rn --include=$INCLUDE_PATTERN --context=3 --color=always $SEARCH_TEXT $START_PATH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment