Last active
June 19, 2023 16:46
-
-
Save mrsarm/8635b70cb79d40be98b627e5a428d614 to your computer and use it in GitHub Desktop.
find-text: Bash script to find text or regex in a given path with context display, and omitting temp folders
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
#!/usr/bin/env bash | |
# | |
# find-text: Find text or regex in a given path with context display, | |
# and omitting temp folders. | |
# | |
if [ "$1" == "-h" -o "$1" == "--help" ] | |
then | |
cat >&2 <<-'EOF' | |
find-text: find text or regex in a given path with context display, | |
and omitting temp folders. | |
The text (literal or regex expressions) is shown along with the path | |
and up to 4 surrounding lines, or `-C LINES` (the `-C` parameter | |
is optional and must be the last one). | |
Usage: find-text LOCATION PATTERN EXPRESSION [-C NUMLINES] | |
Usage example: | |
- Find a JS class "Promotion" that extends the class Component: | |
$ find-text . "*.js" "class Promotion .+Component" | |
- Find at ~/.config/ any file that contains a var "foo" with the | |
value "bar", and show up to 8 surrounding lines: | |
$ find-text ~/.config/ '*' "foo.*=.*bar" -C 8 | |
- Files with ".ts" extension, but without the ".spec" prefix: | |
$ find-text . '*[!.spec].ts' "\.query\(\)" | |
WARNING: use quoted patterns for the filename (using " or '), | |
eg. "*.ext", otherwise the willcards characters *?[] will | |
wrong interpreted raising an error or wrong results. | |
EOF | |
exit | |
fi | |
if [ "$#" -lt 3 -o "$#" -gt 5 ] | |
then | |
echo "find-text: invalid arguments, 3 or 5 required, got $#." | |
echo "Try 'find-text --help' for more information." | |
exit -1 | |
fi | |
LOCATION="$1" | |
PATTERN="$2" | |
EXPRESSION="$3" | |
if [ "$4" == "-C" ] | |
then | |
if [ "$#" -ne 5 ] | |
then | |
echo "find-text: option requires an argument -- 'C'" | |
echo "Try 'find-text --help' for more information." | |
exit -1 | |
fi | |
LINES="$5" | |
else | |
LINES="4" | |
fi | |
find "$LOCATION" -name "$PATTERN" -type f \ | |
! -path '*/node_modules*/*' ! -path '*/.git/*' ! -path '*/.terraform/*' \ | |
! -path '*/build/*' ! -path '*/target/*' ! -path '*/dist/*' ! -path '*/lib/*' \ | |
! -path '*/temp/*' ! -path '*/tmp/*' \ | |
! -path '*/.venv*/*' ! -path '*/.env*/*' ! -path '*/venv*/*' ! -path '*/env*/*' \ | |
! -path '*/__pycache__/*' ! -path '*/*.egg-info/*' \ | |
! -path '*.bak' \ | |
-exec egrep -Hn --color -C "$LINES" -e "$EXPRESSION" {} \; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment