简体   繁体   中英

Use grep to search for a string in files, include subfolders

我必须使用grep命令在文件中搜索特定文本并为此即时消息,但它仅在当前文件夹中搜索。我想要的是使用单个grep命令我可以在当前文件夹以及所有文件夹中搜索特定内容它的子文件夹。我该怎么办???

man grep says

   -R, -r, --recursive
          Read all  files  under  each  directory,  recursively;  this  is
          equivalent to the -d recurse option.

POSIX grep does not support recursive searching - the GNU version of grep does.

find . -type f -exec grep 'pattern' {} \;

would be runnable on any POSIX compliant UNIX.

And even more common is to use find with xargs, say

 find <dir> -type f -name <shellglob> -print0 | xargs grep -0 

where -print0 and -0, respectively, would use null char to separate entries in order to avoid issues with filenames having space characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM