Home > Back-end >  BASH - find and grep specific file in many folders
BASH - find and grep specific file in many folders

Time:10-27

From the current directory, I try to find specific subfolders and grep files with specific extension.

sub-folder structure:

.../1/A
.../1/B
.../2/A
.../2/B
.../3/A
.../3/B

...I want to find each sub-folder contains B in PATH

desired output:

.../1/B
.../2/B
.../3/B

... in each in this sub-folder (B) I want to run grep, but I get no desired output

grep -ro '...match_pattern...' .../1/B/*.out
grep -ro '...match_pattern...' .../2/B/*.out
grep -ro '...match_pattern...' .../3/B/*.out

I tried this code, but no luck. Any advise?

readarray LIST < <(find . -type d B | cut -c 3- )
for i in "(LIST[@]}"
do
     echo $i/*.out
     grep -ro '...match_pattern...' $i*.out
done

I got this and grep looking for two file

NOK outout     - grep -ro '...match_pattern...' .../1/B /*.out
desired output - grep -ro '...match_pattern...' .../1/B/*.out

CodePudding user response:

Using globstar option of bash, this could be done in a simpler way without resorting to find command:

shopt -s globstar
grep -o '…PATTERNS…' **/B/*.out

CodePudding user response:

If I understand correctly, you want:

find "$PWD" -name B -type d -print -execdir sh -c 'grep ... *.out' \;

where

  • $PWD is the current directory; can be substituted with . or any valid directory
  • -name B is the name of the item you are looking for
  • -type d the found item should be a directory
  • -print optionally print out the "hit"
  • -execdir in the directory execute the following command:
  • sh -c '<script>' to prevent expansion of wildcard in "script"
  • grep ... *.out substitute your grep command
  • \; required terminator for find

Not sure why you would want to wrap a find in a for loop.

  • Related