a simple script to check for a given string pattern in any .c, .h, .cpp, .cxx, .m, .mm, etc source files in the current directory and any subdirectories
#! /bin/bash | |
# | |
# simple script to check for a given string pattern in any | |
# .c, .h, .cpp, .cxx, .m, .mm, etc source files | |
# | |
# you can pass your own list of extensions/file patterns as well: | |
# check-for-src-pattern . "foo" .h .cpp .py .sh Makefile | |
# | |
# Dan Wilcox <danomatika@gmail.com> 2014, 2016 | |
# | |
# file type extensions to check (if none given) | |
EXTS=( ".c" ".h" ".cpp" ".hpp" ".cxx" ".m" ".mm" ".sh" ".pd" ".tcl" ) | |
# super simple command parsing | |
if [ $# -lt 2 -o "$1" == "-h" -o "$1" == "--help" ] ; then | |
echo "Usage: check-for-src-pattern directory \"pattern to match\" [types: h cpp ...]" | |
exit 0 | |
fi | |
# main arguments | |
DIR="$1" | |
PATTERN="$2" | |
echo "Checking for \"$PATTERN\" in $DIR" | |
# optional list of file type extensions, overrides EXT | |
if [ $# -gt 2 ] ; then | |
shift; shift | |
EXTS=() # clear | |
while [ $# -gt 0 ]; do | |
EXTS=(${EXTS[@]} $1) | |
shift | |
done | |
fi | |
# build find file type search string from EXT array: | |
# ie. "-name '*.c' -o -name '*.h' -o -name '*.cpp'" | |
for ext in ${EXTS[*]} ; do | |
if [ "$ext" == "${EXTS[0]}" ] ; then # first element | |
TYPES="$TYPES -name \*$ext" | |
else # everything else | |
TYPES="$TYPES -o -name \*$ext" | |
fi | |
done | |
# set internal field separator to endline so filenames with spaces are not broken up | |
IFS=$'\n' | |
# get a list of source files in the given dir | |
cd $DIR | |
files=$(eval "find . -type file \($TYPES \)") | |
for file in ${files[*]} ; do | |
# check against the given pattern, print the filename and grep output if we find a match | |
found=$(grep -n "$PATTERN" "$file") | |
if [ "$found" != "" ] ; then | |
echo "$file:" | |
for line in $found ; do | |
echo " $line" | |
done | |
echo "" | |
fi | |
done |
This comment has been minimized.
This comment has been minimized.
@hamoid No, I had not looked for any existing solutions when I wrote the original script. I started with some usage of |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Nice script! I was surprised to see that the output is soo similar to when I run
ag "struct Settings"
:ag is the silver searcher. I often find it useful that with it you can show context (
-C 3
to show 3 lines around the hit), focus on C++ (-cpp
) and many other features :) Did you know about it?