}

How to find all files containing specific text on Linux? (grep, ack and ag usage examples)

Created:

In this tutorial we are gong to explain how to find a text string on a Linux system on a specific directory or just the whole filesystem. Have you ever struggle to make it work the command find and it doesn't work? Here we explain the proper way of finding text in multiple files.

Finding text in a path usign grep

Using grep is very easy, just try the command:

grep -rnw '/path/to/somewhere/' -e "pattern" *

Explanation: * pattern is the text you are looking inside files. * /path/to/somewhere/ is the directory, if you want to search the whole filesystem use / (you will need to use sudo). * -r or -R is recursive. * -n will show the line number. * -w stands match the whole word.

Optional settings: --exclude, --include, --exclude-dir or --include-dir are very useful when you want to exclude directories (for example excluding .git when searching in a git repo with grep).

Examples

Search all c source code files, filename with .c or .h extensions:

grep --include=\\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern" *

Finding text in a path usign ack

Another alternative to grep is ack, this command will let you search entire file system or the path you want. ack could be easy to use than grep:

ack 'pattern' 

ack will search in the current path where it was executed. The command also allows to use regular expresions in the pattern. If you want to use ack to search in the whole file system just change the directory to the root (/).

Searching string patterns in git repositories

You can always use grep or ack, but there is a tool optimized for searching in git repos called The Silver Searcher. This command is faster than grep and ack when using it in git reports and by default ignores patterns from a .gitignore file.

Example using the silver searcher:

ag pattern ~/code/ 

The ag command is very similar to ack usage. From the official git repository, you can see how well it performs against ack:

ack test_blah ~/code/  104.66s user 4.82s system 99% cpu 1:50.03 total

ag test_blah ~/code/  4.67s user 4.58s system 286% cpu 3.227 total