I have written a code to search for a word recursively with a file system and all it's subdirectories. While it works for the most part, it is having trouble searching folders that contain spaces, e.g. it will find the search word within a directory "Bash_Exercises" but not "Bash Exercises". I know, from the courses I have taken in Bash, it has something to do with utilizing "" to recognize the entire string, but no matter where I put the "" I can't seem to search the folders that have spaces in their name. I figured that I am overlooking something so small, and just wanted a second pair of eyes.
#! /bin/bash
# Navigate to the home directory
cd /Users/michael/desktop
# Ask for word to search
read -p "What word would you like to search for? " word
echo ""
#Find all directories
for i in $(find . -type d)
do
#In each directory execute the following
#In each directory run a loop on all contents
for myfile in "$i"/* ;
do
#If myfile is a file, not a directory or a shell script, echo the file name and line number
if [[ -f "$myfile" ]]; then
#Store grep within the varible check
check=$(grep -ni "$word" "$myfile")
#Use an if to see if the variable "check" is empty, indicating the search word was not found
if [[ -n $check ]]; then
#If check is not empty, echo the folder location, the file name within the folder, and the line where the text shows up
echo "File location: $myfile"
echo "$check"
echo ""
echo "------------------------"
echo ""
fi
fi
done
done
Just as a frame of reference, I am very new to Bash, all self taught through online courses, which can only help so much until you get into non-course examples. I appreciate any and all help.
grep -r?for i in $(find . -type d)loop is fragile in this respect, and that you should use a while read loop to consume find output insteadgrep -r <word> directoryto find the word in any file that is under that subdirectory's tree. If you are trying to do this as an exercise :) then there are other interesting ways