Two ways to find files and grep through them in bash
I love find
because it's a very versatile tool. In the past, I often used find
to get files with multiple extensions and then search through them with grep
. You can do the same with just grep
however!
Here are my test files.
$ for file in $(ls) ; do echo -e "----\nfile: $file has content:\n-"; cat $file; done ---- file: file_a.txt has content: - one two three four five six seven eight nine ten eleven twelve thirteen ---- file: file_b.txt has content: - one two three four five six seven eight nine ten eleven twelve thirteen ---- file: file_c.xml has content: - one two three four five six seven eight nine ten eleven twelve thirteen ---- file: file_d.html has content: - one two three four five six seven eight nine ten eleven twelve thirteen ---- file: file_e.php has content: - one two three four five six seven eight nine ten eleven twelve thirteen
Here is how to use find
and grep
to search through multiple file types for a regular expression.
Look for the word eleven
in all text, xml, html and php files using find
and grep
.
$ find . -type f -regex '^.*\(txt\|xml\|html\|php\)$' -print0 | xargs -0 grep 'eleven' ./file_a.txt:eight nine ten eleven twelve thirteen ./file_b.txt:eight nine ten eleven twelve thirteen ./file_c.xml:eight nine ten eleven twelve thirteen ./file_d.html:eight nine ten eleven twelve thirteen ./file_e.php:eight nine ten eleven twelve thirteen
Now look for the word eleven
in all text, xml, html and php files using just grep
.
$ grep -iER --include "*.txt" --include "*.xml" --include "*.html" --include "*.php" "eleven" . ./file_a.txt:eight nine ten eleven twelve thirteen ./file_b.txt:eight nine ten eleven twelve thirteen ./file_c.xml:eight nine ten eleven twelve thirteen ./file_d.html:eight nine ten eleven twelve thirteen ./file_e.php:eight nine ten eleven twelve thirteen
For grep: -i
is case insensitive, -E
is extended grep (you can use brackets without having to escape them), -R
is recursive searching, so it will search through sub-folders.