How to exclude a folder from a string search

1

>>"results\txtmail.txt" findstr /i /p /s mail %userprofile%\*.txt

Now, what if I want to exclude C:\Users\Username\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5 from the search?

Daniel

Posted 2016-10-03T13:05:09.470

Reputation: 283

The easiest way might be to hide the folder temporarily while you are doing the search. – AFH – 2016-10-03T13:07:48.797

Well that folder is hidden, but it seems that it's getting taken anyway. I can't find the folder by going to the directory, only the batch file can read it. – Daniel – 2016-10-03T13:09:04.800

You can't easily. You probably need to walk the directory tree using for /r and explicitly check for that directory before running findstr. See my so documentation Recursively Visit Directories in a Directory Tree

– DavidPostill – 2016-10-03T21:40:18.540

Answers

2

After finding that findstr ignores the hidden bit and finds files in hidden folders regardless, I then used the for command (which does respect it) to come up with the following, set out for a batch file:-

@echo off
pushd %userprofile%
for /r %%f in (*.txt) do echo %%f | findstr "\Temporary" >NUL: || findstr /i /p mail "%%f" nul:
popd

Notes:-

  • I've not managed to get for /r to work when I add a directory path inside the file match, hence the use of pushd/popd.
  • The first findstr looks for \Temporary (this could be elaborated) in the file path and executes the second findstr only if it's not found.
  • The extra nul: parameter on the second findstr ensures that the file name is printed with the found string: it's normally omitted when there is only one file passed (there may be another way to do this, but I don't often use this command).
  • If you are doing this often you may like to consider moving the internet cache to another directory outside the user profile.

I was checking out this solution when David Postill's comment appeared above. I've only just noticed it, but I'll submit my answer anyway, as it adds a couple of points that need to be considered in any solution.

AFH

Posted 2016-10-03T13:05:09.470

Reputation: 15 470

I tried to run your code and the Content.IE5 folder still appeared, as can be seen in this picture: https://s11.postimg.org/a5xadelmr/Pic_256.png

– Daniel – 2016-10-04T14:54:55.990

I can't test your case directly, as on Win10 the internet cache is organised differently, but I tested on a directory I created with a text file in it, and it worked as expected. However, further investigation shows that text files in the hidden are excluded, but unhidden subdirectories are searched, which seems totally irrational. I have therefore changed my answer to one which works, regardless of the hidden status. – AFH – 2016-10-04T17:47:10.657