help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Storing grep results in variable


From: Martin Schulte
Subject: Re: Storing grep results in variable
Date: Fri, 6 Jun 2025 15:40:45 +0200

Hello Heime,

some hints:

> mysearch ()
>  {
>    local search_dir=$1
>    local search_str=$2
> 
>    if [[ -z "$search_dir" || -z "$search_str" ]]; then
>      echo "Usage: mysearch <directory> <search_string>"

< and > in usage messages look ugly, just omit them - and redirect the message 
to stderr:

echo 'Usage: mysearch directory search_string'>&2

>      return 1

Here it might be a good idea to return 2 to indicate an invocation problem 
while return 1 might indicate that you didn't find a match.

>    fi
> 
>    find "$search_dir" -type f | while IFS= read -r file; do

Filenames containing newlines will break this,

find "$search_dir" -type f -print0 | while read -d '' -r file

will prevent this.

>      matches=$(grep -n -- "$search_str" "$file" | sed 's/:/: /1' )
>      if [[ -n "$matches" ]]; then
>        echo "$file"
>        echo "$matches"

If you can be sure that the content of your files don't change during the run 
of your function you can replace this with

if grep -q -- "$search_str" "$file"; then
  echo "$file"
  grep -n -- "$search_str" "$file" | sed 's/:/: /1'

>        echo
>      fi
>    done
>  }
>

One could consider other solutions like using find's -exec... - I'm curious!

Best regards,

Martin



reply via email to

[Prev in Thread] Current Thread [Next in Thread]