Greg Cox
Greg Cox

Reputation: 227

Windows batch file - For All files in given directory and subdirectories - change file extension to lowercase

My aim: Use Windows batch script to ensure that all files within given directory and subdirectories have a file extension that is lowercase

I have managed to get this far (not very far I admit !)..

for /R c:\test %%G in (*.*) do (
  echo %%G
)

this successfully prints out all files with an extension (inc full path) but how do I check the file extension and ensure it is lowercase (I do not want to make the filename lowercase by the way .. just the extension).

Thanks in advance !

Greg

Upvotes: 3

Views: 4629

Answers (2)

dbenham
dbenham

Reputation: 130819

There are 2 (possibly 3) techniques you need to accomplish your task.

1) You need to parse out the file name and file extension - that is trivial as described in the FOR HELP. (type HELP FOR from the command line)

  • %%~nG = file name
  • %%~xG = file extension

2) You need to store each file extension in a variable and then use code like the following to convert it to lowercase

for %%C 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 "ext=!ext:%%C=%%C!"

You will need to enable delayed expansion with setlocal enableDelayedExpansion at the top of the script.

The above works because the search portion of search and replace is case insensitive.

3) In the unlikely situation that a file extension might containn a !, you need to toggle delayed expansion on and off within the loop. But I seriously doubt you will run into that situation.

Here is a finished, functioning script that disregards point 3.

@echo off
setlocal enableDelayedExpansion
for /r "c:\test" %%F in (*) do if "%%~xF" neq "" (
  set "ext=%%~xF"
  for %%C 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 "ext=!ext:%%C=%%C!"
  ren "%%F" "%%~nF!ext!"
)


Bali C had an interesting idea in his answer, but it did not quite work. I managed to make it work by creating a temporary file with a name consisting only of the file extension in a temporary folder. But it is slower than the above solution.

@echo off
setlocal
set "folder=%temp%\ren%random%"
md "%folder%"
for /r "c:\test" %%F in (*) do if "%%~xF" neq "" (
  copy nul "%folder%\%%~xF" >nul
  for /f "delims=" %%X in ('dir /b /l "%folder%"') do ren "%%F" "%%~nF%%X"
  del /q "%folder%"
)
rd "%folder%"

Upvotes: 8

Bali C
Bali C

Reputation: 31221

This is rushed but something to work with

for /r C:\Folder %%a in (*) do (
    for /f %%s in ('dir /b /l %%a') do (
        ren %%a %%~na%%~xs
    )
)

The dir command with the /l switch is what turns it into lowercase, but from the testing I have done it works sometimes and not others.

Hopefully this can be improved on by another member, but it should work in theory.

Upvotes: 1

Related Questions