0

I'm trying to piece together a batch file that will add the current folder name as a prefix to all files within that folder. In addition this needs to be able to run multiple times without duplicating the prefix.

I found this one that is almost what I need! The only problem is that it duplicates the prefix every time it's run. If someone could point me in the right direction I would be very great full!!

@echo off
pushd "Folder"
for /d %%D in (*) do (
  pushd "%%D"
  for /r %%F in (*) do (
    for %%P in ("%%F\..") do (
      ren "%%F" "%%~nxP_%%~nxF"
    )
  )
  popd
)
popd

This was an answer posted by https://superuser.com/users/109090/dbenham to the question Add folder name to beginning of filename

blodge
  • 3

1 Answers1

0

Next code snippet shows a possible approach (one of many ways); note that operational ren command is merely echoed (echo ren ...) for debugging purposes:

@ECHO OFF
SETLOCAL EnableExtensions
goto :skipProcedures

:testPrefix
call set "newN=%%oldN:*%prfx%=%%"
if /i not "%oldN%"=="%newN%" if /i "%oldN%"=="%prfx%%newN%" set "ToRename="
goto :eof

:skipProcedures
pushd "Folder"
for /d %%D in (*) do (
  pushd "%%D"
  for /r %%F in (*) do (
    for %%P in ("%%F\..") do (
      set "ToRename=Yes"
      set "prfx=%%~nxP_"
      set "oldN=%%~nxF"
      call :testPrefix
      if defined ToRename (
        echo ren "%%F" "%%~nxP_%%~nxF"
      ) else (
        echo prefixed already "%%F" "%%~nxF"
      )
    )
  )
  popd
)
popd

Resources (required reading, incomplete):

JosefZ
  • 13,855