1

How does one rename all folders and files in a folder into UPPERCASE? (if it is possible in its subfolders too)

I have this code, but it converts only files, not folders.

@echo off
setlocal enableDelayedExpansion

pushd %currentfolder%

for %%f in (*) do (
   set "filename=%%~f"

   for %%A in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
      set "filename=!filename:%%A=%%A!"
   )
   ren "%%f" "!filename!" >nul 2>&1
)
endlocal
  • 1
    Does it have to be done via batch? Not that it can't, but there are just so many easier ways via third-party utils. – Karan May 23 '15 at 0:31
0

Non-recursive solution.

I don't know cmd.exe, so I can't fix your script, but if you have Python installed, you can use this script (which should work on all OSes):

import os

files = os.listdir('.')
for f in files:
    newname = f.upper()
    if newname == f:
        continue
    if newname in files:
        print( "error: %s already exists" % newname )
    os.rename(f, newname)

Just save it as upcase_files_folders.py and then run python upcase_files_folders.py in the directory whose files you wants to rename.


Update: Recursive solution.

Sorry, I just realized you wanted a recursive solution.

The following script will walk the subdirectory tree, recording the files and subdirectories to be renamed on a stack. Then it pops the files/subdirectories from the stack one by one and upcases them.

(A two-stage solution is best, to avoid renaming directories in the middle of the traversal. Trying to do it all at once is going to be error-prone and fragile.)

Also, it's probably best to keep a log of the changes in case you run the script in error. This script will record all renames in .upcase_files_folders.log.

from __future__ import print_function
import os

with open('.upcase_files_folders.log','a') as logfile:
    renames = []
    for d, subdirs, fs in os.walk(os.getcwd()):
        for x in fs + subdirs:
            oldname = os.path.join(d, x)
            newname = os.path.join(d, x.upper())
            if x == '.upcase_files_folders.log' or newname == oldname:
                continue
    for (oldname, newname) in reversed(renames):
        os.rename(oldname, newname)
        print( "renamed:  %s  -->  %s" % (repr(oldname), repr(newname)), file = logfile )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.