Skip to content

Instantly share code, notes, and snippets.

@mellertson mellertson/findgrep
Last active Jun 10, 2020

Embed
What would you like to do?
findgrep - finds files matching a file pattern and then grep found files using a regex pattern
#!/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
@mellertson

This comment has been minimized.

Copy link
Owner Author

mellertson commented Jan 5, 2020

NAME

findgrep - finds files matching a file pattern and then grep found files using a regex pattern

USAGE

findgrep DIRECTORY FILE_PATTERN REGEX_PATTERN

DESCRIPTION

findgrep searches for the 1st pattern, FILE_PATTERN, using syntax recognized by find.
And then searches for the 2nd pattern, REGEX_PATTERN, uses regex syntax suitable for grep -e.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.