I am searching for files in my home directory that were modified in the last two minutes that also contain a certain string. I tried with this command:

 find -type d -mmin -2 -ls | grep -Ril "mystring" 

It seems to work but apparently it prints only those files with the given string inside rather than the files last modified 2 minutes ago containing the string. It seems like the first part of the command is not executed.


You had a good attempt with your own suggestion

find -type d -mmin -2 -ls | grep -Ril "mystring"

This would have identified directories (-type d) that had been modified within the last two minutes rather than files (-type f). Piping the output of -ls to grep would usually have searched the generated file names for mystring. However, in this case the -R flag changes the behaviour of grep and it ignores your list of filenames, searching instead through every file at and below the current directory.

So, let's split the problem into two parts

  1. Search for last modified files in the last 2 minutes in your home directory

    find ~ -type f -mmin -2
  2. [Files] which contain a certain String

    grep -Fl 'certain String' {files...}

Now you need to put them together. The {} is a placeholder for the filenames generated by the find from step 1, and the trailing + indicates that the {} can be repeated multiple times, i.e. several filenames

    find ~ -type f -mmin -2 -exec grep -Fl 'certain String' {} +

Changing the grep to echo grep will show you what is being run by the find command; this can be a useful debugging technique:

    find ~ -type f -mmin -2 -exec echo grep -Fl 'certain String' {} +

Please consider running man find and man grep to find out what the various options are, such as the -F and -l in grep -Fl, as otherwise you're not learning anything from the exercise you've been set; you're just copying an answer.

| improve this answer | |
  • Thank you for your time. Yes as you said I'm going to learn more about those in the manuals and how to properly use them. Cheers. – Luca Apr 6 at 11:10

In the zsh shell:

grep -l -F -i 'string' ~/**/*(.Dmm-2)

... where ** matches recursively into subdirectories, and where the .D in (.Dmm-2) means "only match regular files (.), but include hidden files (D)", and where mm-2 means "modified within the last two minutes".

| improve this answer | |

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.