4

To find all file paths with .out extension in subdirectories, I use

find . -name '*.out'

To grep a pattern in all files ending in .out, I use

grep pattern *.out

How do I combine these two commands, so that it finds all files and then greps in those files?

I am looking for an elegant alternative to

grep -r 'pattern' . | grep '.out'
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
nac001
  • 693
  • 2
  • 9
  • 18

2 Answers2

6

You can use globstar, if your shell is Bash version 4+:

shopt -s globstar
grep pattern **/*.out

From Bash manual:

globstar

If set, the pattern ‘**’ used in a filename expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a ‘/’, only directories and subdirectories match.

codeforester
  • 39,467
  • 16
  • 112
  • 140
3

find allows you to run a program on each file it finds using the -exec option:

find -name '*.out' -exec grep -H pattern {} \;

{} indicates the file name, and ; tells find that that's the end of the arguments to grep. -H tells grep to always print the file name, which it normally does only when there are multiple files to process.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264