Skip to content
Advertisement

How do I find all files containing specific text on Linux but not in subdirectories?

Surprisingly i could not find an answer without sub directories. ie I guess without the -R option. What I was looking for was to search for text in a directory but avoid searching in subdirectories. Original post

Tried

grep -nl 'text' /search/path/

But I get the error:

'search/path/ Is a directory`

Whereas if I try with:

grep -rnl 'text' /search/path/` --exclude-dir *

It still searched through subdirectories.

Advertisement

Answer

You can use:

grep 'text' /search/path/*
#                        ^

The * will expand to all the elements in the directory and the absence of -R will avoid going deeper into subdirectories.

The drawback of this approach is that it will exclude the hidden files, since .files do not expand with * alone. If you also want to grep those, you can use:

grep 'text' /search/path/{*,.*}
#                        ____/

This way you will get all elements matching * and .* which is everything.

Finally, if you do not want to get the error message:

search/path/ Is a directory

You can redirect it to /dev/null as follows:

grep 'text' /search/path/{*,.*} 2>/dev/null
#                               _________/
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement