How do I grep recursively in files with a certain extension? [duplicate]

☆樱花仙子☆ 提交于 2021-01-27 14:06:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!