Search code examples
windowsbatch-filerename

Windows batch file pattern rename


I have some file in Windows 7 such as:

AAA_a001.jpg
BBB_a002.jpg
CCC_a003.jpg

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 _ in batch, without knowing in advance the exact names but replacing this pattern.

Can anyone help? Thanks.


Solution

  • @echo off
    pushd "pathToYourFolder" || exit /b
    for /f "eol=: delims=" %%F in ('dir /b /a-d *_*.jpg') do (
      for /f "tokens=1* eol=_ delims=_" %%A in ("%%~nF") do ren "%%F" "%%~nB_%%A%%~xF"
    )
    popd
    

    Note: The name is split at the first occurrence of _. If a file is named "part1_part2_part3.jpg", then it will be renamed to "part2_part3_part1.jpg"