Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep in all directories

I have a directory named XYZ which has directories ABC, DEF, GHI inside it. I want to search for a pattern 'writeText' in all *.c in all directories (i.e XYZ, XYZ/ABC, XYZ/DEF and XYZ/GHI) What grep command can I use?

Also if I want to search only in XYZ, XYZ/ABC, XYZ/GHI and not XYZ/DEF, what grep command can I use?

Thank you!

like image 291
Romonov Avatar asked May 17 '12 16:05

Romonov


People also ask

How do I grep all files in a directory recursively?

Recursive Search To recursively search for a pattern, invoke grep with the -r option (or --recursive ). When this option is used grep will search through all files in the specified directory, skipping the symlinks that are encountered recursively.

Can grep be used for directory?

The grep command is a useful Linux command for performing file content search. It also enables us to recursively search through a specific directory, to find all files matching a given pattern. Let's look at the simplest method we can use to grep the word “Baeldung” that's included in both .

Can you grep multiple files at once?

Grep is a powerful utility available by default on UNIX-based systems. The name stands for Global Regular Expression Print. By using the grep command, you can customize how the tool searches for a pattern or multiple patterns in this case. You can grep multiple strings in different files and directories.


2 Answers

grep -R --include="*.c" --exclude-dir={DEF} writeFile /path/to/XYZ 
  • -R means recursive, so it will go into subdirectories of the directory you're grepping through
  • --include="*.c" means "look for files ending in .c"
  • --exclude-dir={DEF} means "exclude directories named DEF. If you want to exclude multiple directories, do this: --exclude-dir={DEF,GBA,XYZ}
  • writeFile is the pattern you're grepping for
  • /path/to/XYZ is the path to the directory you want to grep through.

Note that these flags apply to GNU grep, might be different if you're using BSD/SysV/AIX grep. If you're using Linux/GNU grep utils you should be fine.

like image 56
逆さま Avatar answered Oct 18 '22 08:10

逆さま


You can use the following command to answer at least the first part of your question.

find . -name *.c | xargs grep "writeText"
like image 44
Hakan Serce Avatar answered Oct 18 '22 09:10

Hakan Serce