1
votes

I have multiple text files in a folder that I am searching the content for and renaming the found files but having a problem. When I run the batch it renames all the found files to the same filename. So if it finds 3 files with the string in them it renames all of them to the same file. Still kinda new to this stuff. I am trying to find the string "test1" inside all the text files and then rename the files found to test1.txt, test1 (2).txt, etc.

@ECHO OFF
@SETLOCAL enableextensions disabledelayedexpansion

SET "sourcedir=C:\test"
SET "searchfor=test1"
FOR /f "delims=" %%a IN ('findstr /m /L /c:"%searchfor%" "%sourcedir%\*.txt"') DO (
 REN "%%a" "%searchfor%.txt"
)
1
Before RENaming you're going to have to add a counter, probably using SET /A, and then use an IF\ELSE expression with EXIST.Compo
its not an answer to your question but you should use ('findstr /m /L /c:"\<%searchfor%\>" "%sourcedir%\*.txt"') to avoid words containing test1 but not just test1Ulug Toprak
@UlugToprak, when stipulating /L the regular expressions \< and \> should be seen as literal characters and fail to match the intended string.Compo

1 Answers

2
votes

change

 REN "%%a" "%searchfor%.txt"

to

 if exist "%searchfor%.txt" (
  set "renamed="
  for /L %%r in (1,1,100) do if not defined renamed if not exist "%searchfor% (%%r).txt" REN "%%a" "%searchfor% (%%r).txt"&set "renamed=%%r"

  ) else (
  REN "%%a" "%searchfor%.txt"
 )

which will for each filename-to-be-changed first detect whether %searchfor%.txt exists, and rename the target file if not. If %searchfor%.txt exists, then set the renamed flag to nothing and loop for %%r = 1 to 100 by steps of 1. If the filename %searchfor% (%%r).txt does not exist, then do the rename and set renamed to (well - any value other than nothing will do - %%r is convenient). Since renamed is now defined, if not defined will be false, so no further rename attempts will be made for that target filename.

(untested)

Note - the syntax is important. Don't try to break the statements over many lines or alter the positions of the parentheses. Just cut-and-paste.

Tip:

Instead of ren use echo ren which will simply REPORT the proposed rename. Obviously, since the file won't actually be renamed, the procedure will report the same new name. Then manually create %searchfor%.txt and try again. Then manually create %searchfor% (1).txt and try yet again. You'll see the proposed new name change. After testing in this manner, change each echo ren to ren and all should proceed smoothly.

(perform tests on a copy with a small number of "hits" to avoid confusion)