Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Thunderbird/52.2.1 Lightning/5.4
On 06/06/2025 at 07:06, Heime via wrote:
Have made this function. I wonder whether variable "matches" will get too
large.
Can I improve this?
mysearch ()
{
local search_dir=$1
local search_str=$2
if [[ -z "$search_dir" || -z "$search_str" ]]; then
echo "Usage: mysearch <directory> <search_string>"
return 1
fi
find "$search_dir" -type f | while IFS= read -r file; do
matches=$(grep -n -- "$search_str" "$file" | sed 's/:/: /1' )
if [[ -n "$matches" ]]; then
echo "$file"
echo "$matches"
echo
fi
done
}
You don't really need the 'find' or, in the sed string, trailing 1 is
automatic. How about using an array (as microsuxx):
(If cd fails, && means rest will not be executed)
cd "$search_dir" && \
for i in *; do
[ -f "$i" ] && \
mapfile -t matches < <(grep -n "search_str" "$i" | sed 's/:/: /')
((${#matches[@]}>0)) && printf '%s\n' "$i" "${matches[@]}"
done
However grep -r will work faster (IMHO)
cd "$search_dir" && \
mapfile -t matches < <(grep -n -r "$search_str" | sed 's/:/: /g')
printf '%s\n' "${matches[@]}"
However this prints the filename on each line.
--
Chris Elvidge
England