How to search within a file in different subfolders using grep?

Asked

Viewed 26 times

0

How can I make a grep searching in a specific file but within several subfolders?

Something like grep -R "busca" /home/apps/*/teste.php

The asterisk is the indication that I want to search in all directories within /home/apps but only inside the archive teste.php that exists within these subfolders.

1 answer

2


Your command (grep -R "busca" /home/apps/*/teste.php) search only the file teste.php in folders that are a level below /home/apps/.

That is, if the file is /home/apps/pasta/teste.php, it is found. But if it is /home/apps/teste.php or /home/apps/pasta/subpasta/teste.php, these will be ignored.

A way to search all subfolders is by using the option --include to specify the file name, and indicate the folder from which the search will be made:

grep -R "busca" --include="teste.php" /home/apps

So he searches for the files called teste.php who are within /home/apps (and the option -R ensures that it will search in all subfolders).

Another option is to use find to fetch the files, and then pass them to grep:

find /home/apps/ -name "teste.php" | xargs grep "busca"

Only that both the above solutions also make the search in /home/apps/teste.php, if there is. But if the idea is to take only from a certain level, you can use the option -mindepth:

find /home/apps/ -mindepth 2 -name "teste.php" | xargs grep "busca"

In the case, -mindepth 2 makes files one level below the folder /home/apps are ignored. That is, /home/apps/teste.php will be ignored, but /home/apps/pasta/teste.php and /home/apps/pasta/subpasta/teste.php nay.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.