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!
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.
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 .
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.
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.
You can use the following command to answer at least the first part of your question.
find . -name *.c | xargs grep "writeText"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With