0

I am writing the below command:

find . -mtime -1 -type f -exec grep -ln '20191122' {} \; | wc -l

which is allowing me to find all files modified within one day, that contain a string of "20191122", and finally then outputting how many files fit the description.

However, there is also sub-directories in the directory I am in, which also have been updated within one day, and they too are counted in the wc -l.

I thought using -type f would just count the 'files' not directories.

Can anyone see the mistake or help?

thank you.

2

Yes, find ... -type f will only find files, but it will do so recursively down into subdirectories.

To only apply the grep to files in the current directory, also use -maxdepth 1 with your GNU find command. This will stop find from descending down more than one level (i.e. into the current directory only).

If you at some point want to do the same on a Unix whose find utility does not implement -maxdepth, you may consider

find . ! -name . -prune -mtime -1 -type f -exec grep -ln '20191122' {} \;

This avoids descending into any other directory than . by using -prune.

As for counting the files, it would be safer to use grep only to detect the pattern in a file and then output something that wc -l would count correctly. If you have filenames containing embedded newlines in their names, wc -l will miscount.

For example:

find . ! -name . -prune -mtime -1 -type f -exec grep -q '20191122' {} \; -exec echo x \; | wc -l

This would output a single line with the character x for each file that contains the string, and wc -l would then count these lines.

| improve this answer | |
  • Since the primary -maxdepth is not one of the useless GNU enhancements, this is supported by most modern find implementations, like BSD find and sfind. But thank you for mentioning that this is not one of the so called standard features. – schily Nov 22 '19 at 11:46
  • @schily Is there something missing from the answer? The user is on Linux, so I'm assuming that they have GNU find. – Kusalananda Nov 22 '19 at 11:51
  • 1
    No, there is nothing missing, but answering with nonstandard enhancements is expected to cause problems for people on platforms that do not implement this specific extension and this is a forum for UNIX. – schily Nov 22 '19 at 11:53
  • 3
    @schily Sorted, I believe. – Kusalananda Nov 22 '19 at 11:56
  • Yes i used the -maxdepth and it worked fine. Thank you – May Nov 25 '19 at 8:06

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.