Home > Software engineering >  How to find files with multiple occurrences of a specific string
How to find files with multiple occurrences of a specific string

Time:04-22

I need help adjusting my batch script so it only picks up files with 2 or more occurrences of the word I am searching for. Currently this gives me all the files that has the word but I do not need the ones where the word occurs only once:

for /f "delims=" %A in ('findstr /i /M "myword" *.txt') do copy "%A" "C:\Desktop\newfolder"

How can I change this so it only copies the text files where "myword" occurs more than once?

CodePudding user response:

@echo off
for %%a in (*.txt) do ( 
  for /f %%b in ('type "%%a"^|find /c "myword"') do (
    if %%b geq 2 echo %%a    [actual count: %%b]
  )
)

Notes:

  • find /c doesn't count occurrences of a string, but lines that contain that word (one or several times) which isn't the same but might be good enough for you.
  • you might want to find /i /c to make it case insensitive (finding "myword" as well as "MyWord")
  • echo %%a [actual count: %%b] is for troubleshooting only, you want to replace it with the copy command in your final code.

CodePudding user response:

As Stephan mentioned, you could use the find command in a for loop to capture the file name and the count of the word in question. You can then evaluate the count based on greater (GTR) than 1 and copy the file to the new location:

for /f "tokens=2,3 delims=: " %%a in ('find /i /c "myword" *.txt') do if %%b GTR 1 copy "%%a" "C:\Desktop\newfolder"
  • Related