Search code examples
batch-filebatch-processingbatch-rename

Rename a file by replacing few characters using Batch script


I'm new to batch scripting and need help here. My file name along with path is

C:\test\My_Test_File_20201006.txt

and I want to rename it as

C:\test\My_File_20201006.txt

using batch script only. I cannot use PowerShell here.

@echo off

set Pattern="Test_File"
set Replace="File"

Rem accepts the filename as cmd line argument
set filename=%1

Rem Update filename
set targetfile=%filename:Pattern=Replace%

Rem Rename the file
Ren %filename% %targetfile%

Exit

Using the above code, My file is renamed as "File". Tried % around the Pattern & replace variables, but no luck. Not sure where I'm going wrong. Tried all possible solutions from the StackOverflow and other tutorials, but none helped.

Edit:

After the proposed solution, getting a syntax error. The code is as below:

@echo off

set "filename=%~nx1"


echo %filename%
echo "%~dp1"
echo "%~dp1%filename:statement_=%"

ren "%~dp1%filename%" "%~dp1%filename:Test_=%"

I call my script from cmd line as:

D:/Test> C:/script/rename.bat C:\test\My_Test_File_20201006.txt

The echo statement correctly prints filename, directory & filename with the directory. Facing issues in rename statement.

Output:

My_Test_File_20201006.txt
"C:\test\"
"C:\test\My_Test_File_20201006.txt"
The syntax of the command is incorrect.

Solution

  • Three things wrong here.

    1. You cannot add the quotes as part of the variable's value. It will actually use them as part of the variable. set variables to have double quotes including the variable name. For instance instead of set Pattern="Test_File" rather do set "Pattern=Test_File"
    2. You never used the variables you've set Replace and Pattern
    3. You either need to enabledelayedexpansion or use call to do the replacement because of the multple % required.
    @echo off
    
    set "Pattern=Test_File"
    set "Replace=File"
    
    Rem accepts the filename as cmd line argument
    set "filename=%~nx1"
    
    Rem Update filename
    setlocal enabledelayedexpansion
    ren "%~dp1%filename%" "!filename:%Pattern%=%Replace%!"
    

    Another method, seeing as you only replace Test_ in your example:

    @echo off
    set "filename=%~nx1"
    ren "%~dp1%filename%" "%filename:Test_=%"
    

    EDIT

    Fixing your example as per the edit.

    @echo off
    
    set "filename=%~nx1"
    
    
    echo %filename%
    echo "%~dp1"
    echo "%~dp1%filename:statement_=%"
    
    ren "%~dp1%filename%" "%filename:Test_=%"