Home > Back-end >  Linux search file with given name containing string recursively
Linux search file with given name containing string recursively

Time:07-15

From Linux shell, Let's say I'm in directory /dir and I want to find, recursively in all subfolders, all the files which contain in the name the string name_string and, inside, the string content_string. name_string might be at the beginning, center or end of the file name. How could I do that?

I was trying to sue grep as:

grep -r content_string /dir/*name_string*

But I haven't been lucky so far.

Thanks!

CodePudding user response:

The find command's -exec grep can solve your question, as in this example:

find /dir -name "*name_string*" -exec grep "content_string" {} /dev/null \;

This, however, will not only show you the name of the file, but also the line, containing the content_string. In case you just want the name of the string:

find /dir -name "*name_string*" -exec grep -l "content_string" {} \;

Obviously, you can use -exec with other commands (head, tail, chmod, ...)

CodePudding user response:

You could also use find with xargs

find /dir -name "*name_string*"|xargs -0 -I '{}' grep "content_string" '{}'

With xargs -0, grep is executed only once and its parameter are all files found with the specified pattern:

grep file1 file2 file3 filen
#it will much faster because there is no overhead in fork and exec like this:
grep file1
grep file2
grep file3
..
  • Related