[batch-file] windows batch file rename

I have some file such as AAA_a001.jpg, BBB_a002.jpg, CCC_a003.jpg in Windows 7 and I'm trying to use batch to rename these file to a001_AAA.jpg, a002_BBB.jpg, a003_CCC.jpg.

Just to swap the content between _.

I have been searching for a while, but still don't know how to do this. Can anyone help? Thanks.

This question is related to batch-file rename

The answer is


I found this solution via PowerShell :

dir | rename-item -NewName {$_.name -replace "replaceME","MyNewTxt"}

This will rename parts of all the files in the current folder.


as Itsproinc said, the REN command works!

but if your file path/name has spaces, use quotes " "

example:

ren C:\Users\&username%\Desktop\my file.txt not my file.txt

add " "

ren "C:\Users\&username%\Desktop\my file.txt" "not my file.txt"

hope it helps


Use REN Command

Ren is for rename

ren ( where the file is located ) ( the new name )

example

ren C:\Users\&username%\Desktop\aaa.txt bbb.txt

it will change aaa.txt to bbb.txt

Your code will be :

ren (file located)AAA_a001.jpg a001.AAA.jpg

ren (file located)BBB_a002.jpg a002.BBB.jpg

ren (file located)CCC_a003.jpg a003.CCC.jpg

and so on

IT WILL NOT WORK IF THERE IS SPACES!

Hope it helps :D


I am assuming you know the length of the part before the _ and after the underscore, as well as the extension. If you don't it might be more complex than a simple substring.

cd C:\path\to\the\files
for /f %%a IN ('dir /b *.jpg') do (
set p=%a:~0,3%
set q=%a:~4,4%
set b=%p_%q.jpg
ren %a %b
)

I just came up with this script, and I did not test it. Check out this and that for more info.

IF you want to assume you don't know the positions of the _ and the lengths and the extension, I think you could do something with for loops to check the index of the _, then the last index of the ., wrap it in a goto thing and make it work. If you're willing to go through that trouble, I'd suggest you use WindowsPowerShell (or Cygwin) at least (for your own sake) or install a more advanced scripting language (think Python/Perl) you'll get more support either way.


I rename in code

echo off

setlocal EnableDelayedExpansion

for %%a in (*.txt) do (
    REM echo %%a
    set x=%%a
    set mes=!x:~17,3!

    if !mes!==JAN (
        set mes=01
    )

    if !mes!==ENE (
        set mes=01
    )

    if !mes!==FEB (
        set mes=02
    )

    if !mes!==MAR (
        set mes=03
    )

    if !mes!==APR (
        set mes=04
    )

    if !mes!==MAY (
        set mes=05
    )

    if !mes!==JUN (
        set mes=06
    )

    if !mes!==JUL (
        set mes=07
    )

    if !mes!==AUG (
        set mes=08
    )

    if !mes!==SEP (
        set mes=09
    )

    if !mes!==OCT (
        set mes=10
    )

    if !mes!==NOV (
        set mes=11
    )

    if !mes!==DEC (
        set mes=12
    )

    ren %%a !x:~20,4!!mes!!x:~15,2!.txt 

    echo !x:~20,4!!mes!!x:~15,2!.txt 

)