Let's say I'm searching for all files with .log extension that contain the text of abc.

When searching for files with any extension would look like (Ref.: https://unix.stackexchange.com/a/16140/38353 )

find / -xdev -type f -print0 | xargs -0 grep -H "abc"

How could we modify this so that it will search only for files with .log extension?

I'll be more than happy if you show a better command.



Add -iname "*.log" after / to your find command. Refer to man page for more info

A more detailed answer

The task at hand is the following:

  1. List files that match pattern *.log
  2. Execute grep per each file to find whether or not it contains a specific string.
  3. List the filename that has a match on the stdout

The example of how that can be accomplished can be seen bellow:

$ find /var/log -iname "*.log" -exec grep -l 'wlan' {} \+                      

Essentially there's 3 things at play:

  • find does the job of finding files AND calling grep per list of filenames in the -exec ...{} \+ structure, where {} will be substituted with all the filenames found.
  • -iname "*.log" can provide case-insensetive matching of the filenames
  • -exec . . .{} \+ calls the low-level execve function that will spawn grep -l with the list of all the files found in front of it ( in the place of {} ).
  • The \+ is the option that specifies for execve to pack as any files as possible in front of grep (the limit is set by ARG_MAX variable, is specific to exec, and for Ubuntu is at 2097152 as can be shown by getconf ARG_MAX command ). Once the limit is reached, exec will repeat the call to grep with more files packed as arguments. The \ is necessary to ensure + is interpreted as argument to find and not as another shell command.
  • the -l option or grep shows files with matched string. -L would match files without the string.
  • Thanks, Serg. The command shows the contents of the files are being searched. Is there a way not to show the content? Because I only need the list of file – Askar Apr 14 '16 at 1:40
  • @oscar yes, the -l flag for grep will do that. I am on mobile so it's hard to post complete answer. I'll edit as soon as I'm home – Sergiy Kolodyazhnyy Apr 14 '16 at 1:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.