0

I need to write a windows batch script. Starting from a given directory, I need to check whether there is at least one occurrence of a given text in every file with a given file name.

E.g.: Starting with the directory C:\MyDir, I need to check this directory and all subdirectories for files with the name "MyFile.txt". Every file found must have at least one occurrence of the text "MyText".

What I have so far is this:

FOR /R C:\MyDir %%f in (MyFile.txt*) do ( FINDSTR /i /c:"MyText" %%~f )

Problems:

  • This would also match for files with the name MyFile.txtXXX
  • It does only print occurrences but does not "return" whether such an occurrency is found. This code is inside a batch script which must exit with an error, if there is one file without such an occurrence.
2
  • why MyFile.txt*? Can this be translated to "find all 'MyFile.txt' that does (not) contain 'MyText')" ? Commented Aug 10, 2016 at 14:03
  • Yes, that's the goal: "find all 'MyFile.txt' that do not contain 'MyText' Commented Aug 10, 2016 at 14:20

2 Answers 2

1

findstr /v does not work like intended here, so you have to use a little trick: use findstr and use it's errorlevel to find "string not found":

for /r %%a in (myfile.txt) do findstr /i "MyText" %%a >nul && echo yes: %%a|| echo no:  %%a
  • for /r is recursive (search in subdirectories too) (use for instead of findstr /s to process each file one after the other to be able to check errorlevel for each single file instead of the complete findstr /s list)
  • && works as "if previous command (findstr) was successful, then"
  • || works as "if previous command (findstr) failed, then"
Sign up to request clarification or add additional context in comments.

Comments

1

Read findstr /?: Searches for strings in files.

FINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:file]
        [/C:string] [/G:file] [/D:dir list] [/A:color attributes] [/OFF[LINE]]
        strings [[drive:][path]filename[ ...]]
  …
  /S         Searches for matching files in the current directory and all subdirectories.
  …

Next command should find and display all matches:

FINDSTR /S /i /c:"MyText" C:\MyDir\MyFile.txt

Next command should find all matches and display only (fully qualified) file names:

FINDSTR /M /S /i /c:"MyText" C:\MyDir\MyFile.txt

1 Comment

Thx for your answer. However, with this statement I have no possibility to find files without the given occurrence.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.