Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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 <> 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
# main arguments
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)
# 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"
# set internal field separator to endline so filenames with spaces are not broken up
# 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"
echo ""

This comment has been minimized.

Copy link

@hamoid hamoid commented Apr 1, 2018

Nice script! I was surprised to see that the output is soo similar to when I run ag "struct Settings":

119:    struct Settings{

44:     struct Settings;
102:    struct Settings: public ofGLESWindowSettings {

158:    struct Settings {

60:     struct Settings {

22:     struct Settings;
208:    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?


This comment has been minimized.

Copy link
Owner Author

@danomatika danomatika commented Jan 22, 2021

@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