Find files containing my text
Searching a given text inside a set of files is a very common use case. There are different ways of doing it depending on how deep you need search through the directory tree.
Finding in files under the current directory
To find a given text in files under the current directory alone, you can simply use the grep command as shown below:
1 2 3 |
grep <text to find> <files list pattern> |
For eg. To find the text “apache” in all files with extension .txt run the following command. The output would show the file name followed by the line in the file containing the searched text.
1 2 3 4 |
$ grep apache *.txt license.txt: http://www.apache.org/licenses/ license.txt: http://www.apache.org/licenses/LICENSE-2.0 |
To omit the occurrences of the searched text and to list only the file names, add the –l option.
1 2 3 |
$ grep –l apache *.txt license.txt |
Finding in files recursively in all sub-directories
To find in files recursively under all sub-directories, use the combination of find and grep commands as shown below:
1 2 3 |
find <directory> [-name <file name patter>] | xargs grep <text to find> |
For eg. To find the text “apache” in all files under all directories under the current directory run the following command. The output would list all the files under all directories and sub-directories followed by the line containing the occurrence of the searched text. As said earlier, to list just the file names, add the –l option to the grep command.
1 2 3 4 5 |
$ find . -name "*.txt" | xargs grep apache ./lib/readme.txt:- Ant 1.6.2 (http://ant.apache.org) ./license.txt: http://www.apache.org/licenses/ ./license.txt: http://www.apache.org/licenses/LICENSE-2.0 |
How does it work?
The find command lists the files to be searched based on the given filename pattern. It does that recursively by scanning all the directories and sub-directories. Its output is a list of file paths separated by a new line character. The grep command needs to take in the file list generated by the find command as an argument list and search the given text in contents of those files. But, if you pipe the output of the find directly to grep, grep will search in the output itself and will not understand that it has to consider the output as the list of input file arguments. So, to convert the output to a list of argument use xargs command. xargs passes the argument list to its input, which is the grep command in this case.