问题
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'
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/51952546/how-do-i-grep-recursively-in-files-with-a-certain-extension