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:

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.

To omit the occurrences of the searched text and to list only the file names, add the –l option.

 

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:

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.

 

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.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Previous article

Find the process using a given port

Next article

Protection of Java Based Software