Search code examples
excelwindowsbatch-filebatch-rename

Batch file : how to rename a .xls file when another .xlsx file present in same folder?


I have a folder with 1 batch file and 2 excel files - old.xls and new.xlsx.

I need to rename both these files to test.xls and test.xlsx by using the batch file in the same folder.

When I try to rename the .xlsx file I can successfully do it by using the following command:

ren *.xlsx test.xlsx

But when i try doing the same for the .xls file I get the following error :

ren *.xls test.xls

A duplicate file name exists, or the file
cannot be found.

Can someone tell me how to do this? I am new to batch files.


Solution

  • @ECHO OFF
    SETLOCAL
    SET "sourcedir=U:\sourcedir"
    PUSHD "%sourcedir%"
    
    
    ECHO directory before xlsx rename
    DIR /x /a-d
    REN *.xlsx test.xlsx
    ECHO ============================
    ECHO directory before XLS rename
    DIR /x /a-d
    ECHO.
    FOR %%a IN (*.xls) DO ECHO "XLS" name found: %%a
    ECHO.
    FOR %%a IN (*.xls) DO IF /i "%%~xa"==".xls" REN "%%a" test.xls
    ECHO ============================
    ECHO directory after XLS rename
    DIR /x /a-d
    
    
    popd
    GOTO :EOF
    

    By default, every file or directory whose name does not comply with the DOS "8.3" filename convention (name of up to 8 characters, extension of up to 3, separated by a dot) will be assigned a "short name" that does comply.

    The above code (I use u:\sourcedir as a test directory) will show the steps. Note that dir /x shows shortname and longname. /a-d suppresses directorynames).

    so - the magic is to check that the fullname-extension actually is .xls.