Last active
January 22, 2021 13:55
-
-
Save danomatika/9173240 to your computer and use it in GitHub Desktop.
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
This file contains 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 | |
# | |
# 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 <[email protected]> 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 |
@hamoid No, I had not looked for any existing solutions when I wrote the original script. I started with some usage of find
then ended up wrapping it in a script and using it more and more. It works well for me following the Unix philosophy. :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?