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)
REN
aming you're going to have to add a counter, probably usingSET /A
, and then use anIF\ELSE
expression withEXIST
. – Compo('findstr /m /L /c:"\<%searchfor%\>" "%sourcedir%\*.txt"')
to avoid words containing test1 but not just test1 – Ulug Toprak/L
the regular expressions\<
and\>
should be seen as literal characters and fail to match the intended string. – Compo