grep: display filename once, then display context with line numbers
I would change a few things about.
find_code() {
# assign all arguments (not just the first ${1}) to MATCH
# so find_code can be used with multiple arguments:
# find_code errorCode
# find_code = 1111
# find_code errorCode = 1111
MATCH="$@"
# For each file that has a match in it (note I use `-l` to get just the file name
# that matches, and not the display of the matching part) I.e we get an output of:
#
# srcdir/matching_file.c
# NOT:
# srcdir/matching_file.c: errorCode = 1111
#
grep -lr "$MATCH" ${SRCDIR} | while read file
do
# echo the filename
echo ${file}
# and grep the match in that file (this time using `-h` to suppress the
# display of the filename that actually matched, and `-n` to display the
# line numbers)
grep -nh -A5 -B5 "$MATCH" "${file}"
done
}
You could use find
with two -exec
s, the second one will be executed only if the first one is successful, e.g. searching only in .cpp
, .c
and .cs
files:
find_code() {
find ${SRCDIR} -type f \
\( -name \*.cpp -o -name \*.c -o -name \*.cs \) \
-exec grep -l "= ${1}" {} \; -exec grep -n -C5 "= ${1}" {} \;
}
so the first grep
prints the filenames that contain your pattern and the second one will print the matching lines+context, numbered, from the respective files.