Search code examples
windowsfor-loopbatch-filecmdfile-rename

Batch rename: skipping already renamed files


so in one other recent question i needed to find a solution to bulk renaming files by adding .ab into the filename. I succeeded in doing that, but now i face a different problem. Every time i run the batch file, it appends .ab to all the files even those, already renamed. I tried fixing the problem in the following way, which doesn't work.

rem @echo off

FOR /R "C:\Users\" %%G in (*.txt) DO (
  %%G|findstr /i /L ".ab">nul
  IF errorlevel 1 (
    REN "%%G" "%%~nG.ab.txt"
  ) ELSE (
    skip %%G
  )
)

pause

Essentially i need to check if the file name already contains ".ab" in its name and then either skip or add .ab depending on the result. I would appreciate any help.


Solution

  • Use a For /F loop, instead of For /R. In addition, instead of using the Dir command with its /S option, (which will output items ending with .txt*), use Where with its /R option instead, (which will output items ending with .txt).

    Single line example, (excludes those basenames ending with, not containing, .ab):

    @For /F "Delims=" %%G In ('^""%__AppDir__%where.exe" /R "C:\Users" "*.txt" 2^>NUL^|"%__AppDir__%findstr.exe" /IV "\.ab\.txt$"^"')Do @Ren "%%G" "%%~nG.ab%%~xG"
    

    Don't forget to change C:\Users and/or both instances of .txt and ab as/if necessary.