Last active
June 10, 2020 04:39
-
-
Save mellertson/490742488d12d16cb2c779c592827029 to your computer and use it in GitHub Desktop.
findgrep - finds files matching a file pattern and then grep found files using a regex pattern
This file contains hidden or 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 | |
RED="\e[31m" | |
GREEN="\e[32m" | |
BOLD="\e[1m" | |
ITALIC="\e[3m" | |
UNDERLINE="\e[4m" | |
END="\e[0m" | |
function usage { | |
echo -e "" | |
echo -e "\e[1m\e[32mNAME\e[0m " | |
echo -e "\tfindgrep - finds files matching a file pattern and then grep found files using a regex pattern" | |
echo -e "\e[1m\e[32mUSAGE\e[0m" | |
echo -e "\t\e[1m\e[32mfindgrep\e[0m \e[1m\e[31mDIRECTORY FILE_PATTERN REGEX_PATTERN\e[0m" | |
echo -e "" | |
echo -e "\e[32m\e[1mDESCRIPTION\e[0m" | |
echo -e "\t\e[1m\e[32mfindgrep\e[0m searches for the 1st pattern, \e[31m\e[1mFILE_PATTERN\e[0m, using syntax recognized by \e[1m\e[32mfind\e[0m." | |
echo -e "\tAnd then searches for the 2nd pattern, \e[31m\e[1mREGEX_PATTERN\e[0m, uses regex syntax suitable for \e[1m\e[32mgrep -e\e[0m." | |
echo -e "" | |
echo -e "\e[32m\e[1mEXAMPLE\e[0m" | |
echo -e "\tTo find all files in the current directory ending in \e[31m\e[1mnotes.txt\e[0m, which contain the text \e[31m\e[1multimate question\e[0m" | |
echo -e "\tfollowed by the text \e[31m\e[1m42\e[0m, you would issue the following command:" | |
echo -e "" | |
echo -e "\t\tfindgrep ./ '*notes.txt' 'ultimate question.*42'" | |
echo -e "" | |
} | |
# if correct number of arguments are not given, print usage | |
if [[ -z "$1" ]] || [[ -z "$2" ]] || [[ -z "$3" ]] | |
then | |
usage | |
exit 0 | |
fi | |
function get_random_filename { | |
FNAME="/tmp/findgrep_$RANDOM.txt" | |
} | |
function create_tmp_file { | |
get_random_filename | |
while [[ -f "$FNAME" ]]; do | |
echo -e "\t$FNAME already exists, getting a new random filename..." | |
get_random_filename | |
done | |
} | |
create_tmp_file | |
# execute the find and grep commands | |
find $1 -type f -iname $2 -print0 > $FNAME | |
if [[ -f $FNAME ]]; then | |
LINE_COUNT=`cat $FNAME | wc -m` | |
if [ ! "$LINE_COUNT" -eq "0" ]; then | |
xargs -0 -a $FNAME grep -i -e "$3" --color=always -H -n | |
fi | |
else | |
echo "file $FNAME does not exist..." | |
fi | |
rm $FNAME 2>/dev/null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NAME
USAGE
DESCRIPTION