Created
December 18, 2024 10:25
-
-
Save djfm/34878a33cc3e42a24658bd44a6d9d11d to your computer and use it in GitHub Desktop.
grep the presence of some expression but specifically in text files, should not attempt to search binaries (not thoroughly tested)
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 | |
search_exp=$1 | |
search_path=$2 | |
# if search path is not provided, | |
# use current directory and signify it to the user | |
if [ -z "$search_path" ]; then | |
search_path="." | |
echo "No search path provided, using current directory" | |
echo | |
fi | |
# if search expression is not provided, | |
# exit with error and display usage message to the user | |
if [ -z "$search_exp" ]; then | |
echo "Usage: t-grep <search_expression> [search_path]" | |
echo | |
echo "Searches for the given expression in text files in the given path." | |
echo "If no path is provided, searches in the current directory." | |
echo "The <search_expression> is obviously mandatory." | |
echo | |
echo "There will probably be access rights errors as usual with find and grep, " | |
echo "they will not be displayed here." | |
exit 1 | |
fi | |
echo "Searching for \"$search_exp\" in \"$search_path\", considering only text files..." | |
echo | |
find "$search_path" \ | |
-type f \ | |
-exec sh -c "file -b --mime-type \"\$1\" | grep -q \"text/\" && \ | |
grep -q -E \".{0,10}$search_exp.{0,10}\" \"\$1\" && \ | |
echo \"In file '\033[1;34m\$1\033[0m':\" && \ | |
grep --color=auto -E -o \".{0,10}$search_exp.{0,10}\" \"\$1\"" _ {} \; \ | |
2>/dev/null | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment