I need to find a regex string in multiple files under multiple user directories and subdirectories. I've used a grep command to find the actual data, but have been manually running it inside each user diretory and recursively grep'ing for the string. I'd like to start at the root dir and have a small script create a file for each user dir and record the output of the grep for that user in a text file. I have not had any luck figuring it out on my own using a for loop.
For Loop: I dont really know how or where to put the grep command.
#!/bin/bash
IFS=$'\n'
for dir in $(find /Users/brian/Documents/ -maxdepth 1 -path . -type d);
do
for subdir in $(find "$dir" -mindepth 2 -type d);
do
base_dir=$(basename $dir)
base_subdir=$(basename $subdir)
touch "$base_dir"/"$base_subdir"/"$base_dir"_"$base_subdir".txt
done
done
grep -irnE '<img [^>]*src=\"?http:' /path/to/user/ -s > /path/to/output.txt &
My expected result for the grep works just fine, but I don't really know how to integrate the grep into the for loop.
You can try the following recursive script. It greps each directory only once, but then collects the grep results of the sub directories to propagate them in the current directory. Make sure the name of the script matches the call in line 14 and that it can be found in the path variable.
#!/bin/bash
results_file=my_grep_results.txt
files_to_search="*.srt"
pattern='[Tt]ime'
OIFS="%IFS"
IFS=$'\n'
echo "scanning $(pwd) - ${1}..."
cd "$1"
for subdir_to_search in $(find -maxdepth 1 -type d) ; do
if [ "${subdir_to_search}" != "." ] ; then
grep_recursive.sh "${subdir_to_search}"
cat "${subdir_to_search}/${results_file}" >> "${results_file}"
fi
done
grep "${pattern}" ${files_to_search} >> "${results_file}" 2> /dev/null
IFS="$OIFS"