Question by:


    The compilation, plus my own code that follows, took well over 12 hours of work in research, tests, & getting this together.

    My Request? One or more of:
    -> A general "find & replace"  to rename files in a folder: the MS-DOS code must replace a specified string in any part of  a name with another specified string (which may be null or other). You can use the info below to help out.  Anyone up for the  challenge?

    -> Failing that, then points  to any rename routine that's uniquely functional and worthy of being added to this collection.  (& If solution also works in Win98, Joy! :))

    -> Still nothing? Then points to whoever locates free internet documentation of the ":~4%" feature as used in a rename command. (see "Please let me know" under 'Remove a prefix' below) .

    N o t e s :
    - Some code I've condensed using the '&' sign (for NT/2k/XP) or the '|' sign (for 98) which often allow use of multiple commands on one line. See "Can you type more than one command at one command prompt?". (Some of what fails:  '|' after 'if' or 'call' statement; '&'  after 'if', '&' after 'set' as in:set x=y&if  %x%==y echo y; the set doesn't happen until AFTER a line break! Weird language...) Note: to echo the '&'  you must 'echo ^&'
    -The code-author's EE id usually follows each code block.
    -Some code  just 'echo's the rename commands to be run. Must remove the 'echo' from 'echo ren' to actually do the deed.

    ~~ Add a suffix (*_n): ~~
    FOR %%f IN (*.*) DO ren %%f %%f_n

    ~~ Remove a suffix (Remove b in   a_b.c) ~~
    @echo off&for %%f in (*_*.*) do call :ProcessFile %%f
    goto :eof
    for /F "delims=_. tokens=1,3" %%c in ("%1") do echo ren "%1" "%%c.%%d"

    ~~ Add a prefix (S1*): ~~
    for %%i in (*.*) do move %%i s1%%i  
    for /f "delims=" %i in ('dir/b') do ren "%i" "s1%i"

    The DOS command shell, to include WinNT/2K/XP has always acted strangely when using wildcards in the middle of filenames. The truth is, that wildcards almost never work correctly when the wildcard is in the middle of the filename.
    For example:
    "REN *.TXT *-S1.TXT" will result in the file TEST1.TXT being renamed to TEST1.TXT-S1.TXT
    "REN *.TXT S1-*.TXT" will result in the file TEST1.TXT being renamed to S1-T1.TXT

    ~~ Remove a prefix -- a fixed # of bytes. Replace with new prefix. (SFyymmddhhmm.csv->SISCR12mmddhhmm.csv ) ~~
    *** ":~4%" crop feature: where is it documented? Please let me know... - callrs***
    @echo off
    for %%i in (SF03*.CSV) do (set fname=%%i) & call :rename
    goto :eof
    ::Cuts off 1st 4 characters of fname, then appends prefix
    ren %fname% SISCR12%fname:~4%
    goto :eof

    ~~ Add a prefix to numbers-only file-name: ~~
    for /f %%a in ('dir /b *.txt ^| findstr /I /X /R /C:^[0-9]*.txt') do ren %%a prefix%%a
    ::or for 8-digit files only:
    for /f %%a in ('dir /b *.txt ^| findstr /I /X /R /C:^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9].txt') do ren %%a pyxbl%%a

    ~~ Rename to random number: ~~
    @echo off&setlocal
    set FileMask=*.bmp
    for /f "tokens=*" %%a in ('dir /b /a:-d "%FileMask%"') do call :process "%%a"
    goto :eof
    set rnd=%Random%
    if exist %rnd%%~x1 goto loop
    ECHO ren %1 %rnd%%~x1
    goto :eof

    ~~ ??? wildcards ~~
    ren ???xxx??? ???zzz???

    ~~ Recurse through all sub-directories (excluding current), changing extension: ~~
    @echo off
    for /f "tokens=1 delims=" %%a in ('dir /s /b /ad') do if exist "%%a\*.asp" echo ren "%%a\*.asp" *.html >> rename.cmd

    ~~ Rename all jpg files in a folder tree (to cover.jpg): ~~
    @for /R c:\ %%f in (*.jpg) do echo rename "%%~ff" cover.jpg

    ~~ Recurse thru sub-directories, renaming files ~~
    FOR /r %1 IN (.) do MYRENAMEBAT.BAT %1
    ::RaviPal .   Where the bat file is:
    @echo off&echo This will rename all files containing '_fixed'.
    echo CHANGE THE FOLDER&cd %1&Pause
    rename * *.xxx
    rename *.zip *.zip.old
    Rename *.xxx *.zip

    ~~ Suffix a date: ~~
    ren c:\temp\abc.txt abc%date:~4,2%-%date:~7,2%-%date:~10%.txt
    @echo off&if [%1]==[] goto :usage
    set strFile=%1
    set strExt=%strFile:~-4%
    set strNew=%strFile:~0,-4%
    ren strFile %strNew%%date:~6,4%%date:~0,2%%date:~3,2%.%strExt%
    goto :eof
    RenFile OriginalFilename

    ~~ Copy, adding system date: ~~
    FOR /F "TOKENS=2-4 DELIMS=/ " %%F IN ('DATE /T') DO (SET TODAY=%%F%%G%%H)
    COPY /Y /B C:\TEMP\*.VCH C:\Upload\Combined.vch
    REN C:\Upload\Combined.vch Combined-%TODAY%.vch

    ~~ Rename jpg files to their file-time-stamp: ~~
    FOR %%V IN (*.jpg) DO FOR /F "tokens=1-5 delims=/: " %%J  IN ("%%~tV") DO IF EXIST %%L%%J%%K_%%M%%N%%~xV (ECHO Cannot rename %%V) ELSE (ECHO RENAME "%%V" %%L%%J%%K_%%M%%N%%~xV & RENAME "%%V" %%L%%J%%K_%%M%%N%%~xV)
    ::From PC-Mag

    ~~ Copy, appending current date: ~~
    @echo off&setlocal
    ::Change these as necessary
    set Source=d:\temp\&set Dest=d:\temp2\
    if "%Source:~-1%" NEQ "\" set Source=%Source%\
    if "%Dest:~-1%" NEQ "\" set Dest=%Dest%\
    if not exist %Source% goto :Error
    if not exist %Dest% goto :Error
    set Today=%date:~0,2%%date:~3,2%%date:~6,4%
    for %%z in (%Source%*.*) do call :ProcessFile "%%z"
    goto :eof
    set FilePath=%~1&set FileName=%~n1&set FileExt=%~x1
    ::Remove the echo from the next line to do the actual copy
    echo copy "%FilePath%" "%Dest%%FileName%_%Today%%FileExt%"
    goto :eof
    echo Either the source or destination directory does not exist

    ~~ Date Image Files based on date taken etc. ~~
    - Rename image files based on the value of EXIF and IPTC fields
    - How to read EXIF Tags  (Similar to above)
    - Powerbatch
    - Photo Studio
    -  -

    ~~ Rename all files to 3-digit Number (001, 002, ...): ~~
    :: Change c:\temp\1\ with the folder your files are in. Don't put .bat files in that folder.
    @echo off&setlocal&set count=0
    for /f "usebackq delims=" %%x in (`dir /a:-d /b "C:\TEMP\*.*"`) DO CALL :NUMBER %%x
    goto :EOF
    set NAME=%~n1%
    set EXT=00%count%
    set EXT=%EXT:~-3%
    echo ren "%1" "%NAME%.%EXT%"
    set /a count+=1
    goto :EOF
    ::MaartenG (-)
    -->Below is MS-DOS 6 version, with c:\temp\1\ being path to files to rename.
    --------------------- rename00.bat
    ECHO OFF|set n1=0|set n2=0|set n3=0
    for %%a in (c:\temp\1\*.*) do call renameit.bat %%a
    set n1=|set n2=|set n3=|set nx=
    --------------------- renameit.bat
    rename %1 %n3%%n2%%n1%
    set nx=%n1%| call incnx.bat
    set n1=%nx%
    if not %n1%==0 goto end
    set nx=%n2%| call incnx.bat
    set n2=%nx%
    if not %n2%==0 goto end
    set nx=%n3%| call incnx.bat
    set n3=%nx%
    ---------------------------- incnx.bat
    if %nx%==0 goto number0
    if %nx%==9 SET nx=0
    if %nx%==8 SET nx=9
    if %nx%==7 SET nx=8
    if %nx%==6 SET nx=7
    if %nx%==5 SET nx=6
    if %nx%==4 SET nx=5
    if %nx%==3 SET nx=4
    if %nx%==2 SET nx=3
    if %nx%==1 SET nx=2
    goto end
    SET nx=1

    ~~ Rename all files to prefix + a number  (images_1.jpg, images_2.jpg ...) ~~
    @echo off&set /a cnt=1
    for %%a in (*.jpg) do call :PROCESS "%%a"
    goto :EOF
    echo rename %1 images_%cnt%.jpg
    set /a cnt+=1

    ~~ Replace First Dot ~~
    @echo off&setlocal&echo.&set Test=FALSE
    if %1.==. goto Syntax
    if %1==/? goto Syntax
    if %1==-? goto Syntax
    if %2.==. goto :begin
    if /i not %2==/test goto Syntax
    set Test=TRUE
    for /f %%a in ('dir /b /a:-d %1') do (
      set FilePath=%%~dpa&set FileName=%%~na&set FileExt=%%~xa&call :process )
    goto :eof
    if %FileName%==%FileName:.=% goto :eof
    for /f "tokens=1* delims=." %%a in ("%FileName%") do set NewFileName=%%a-%%b
    echo %FilePath%%FileName%%FileExt% --^> %NewFileName%%FileExt%
    if /i %Test%==TRUE goto :eof
    ren "%FilePath%%FileName%%FileExt%" "%NewFileName%%FileExt%"
    goto :eof
    echo %~nx0&echo.
    echo Replaces first ".", if any, of the file name with a "-", but not the extension&echo.
    echo Syntax:  &echo repdot ^<File^> [/test]&echo.
    echo ^<File^>: The specified directory/file is processed
    echo /test:  No renaming is done, files that would be renamed are only displayed.

    ~~ Move tokens around ~~
    @echo off&setlocal&set Folder=%1&set Pattern=samptest.txt.*
    dir /b %Folder%%Pattern% 1>NUL 2>NUL
    if errorlevel 1 goto Syntax
    for /f %%a in ('dir /b %Folder%%Pattern%') do (
      set File=%%a&  call :process)
    goto :eof
    echo Processing %File% ...
    for /f "tokens=1-3 delims=." %%a in ("%File%") do (
      set Name=%%a
      set Number=%%c)
    set NewFile=%Name%%Number%.edi
    :: *** Remove the "echo" in the next line to "arm" the script
    echo ren %Folder%%File% %NewFile%
    goto :eof
    echo ediren.cmd&echo.
    echo Renames files matching samptest.txt.^<Number^>
    echo to samptest^<Number^>.edi&echo.&echo Syntax:
    echo ediren [^<Target Directory^>]&echo.
    echo If no target directory is specified, the current directory is used.
    echo The directory must be specified including the trailing "\"!

    ~~ Other ~~
    MoveFile - Rename an existing file or a directory
    renaming files but exclude newest
    Comparing,moving, and renaming files in a DOS atmosphere
    A batch rename operation which cannot be done with dos, can someone do it in/with vbscript?

    ~~ General Renaming Utilities referenced in posts: * means freeware ~~ File Renaming Tools* Bulk Rename Utility* Opensource Rename-it* Rename Master* Rename4u (Kelly Software)* Lupas Rename 2000*  IrfanView* (File-->Batch Conversion/Rename...) Better File Rename (Not Free) File and MP3 Tag Renamer (Trial)

    ~~ Below is my own code from answer to "Rename Files Instantaneously": ~~
    :: renlef+.bat
    :: Prefix ADD utility for file names: Adds the specified prefix and delim (& optionally isolates delim by spaces) to all files that have specified extension
    :: Doesn't perform the rename, but generates &  writes the commands to a bat file
    :: If prefix+delim is already in the original name, then ignores the file unless doall=1
    :: Arguments:
    ::   %1 - Prefix to add
    ::   %2 - Delimiter to add
    ::   %3 - Extension of file
    ::   %4 - Space - Set to 1 to add space to both sides of delim
    ::   %5 - Doall - See "If prefix+delim..." note above
    :: v1.01  By Ravinder Singh ('wiz' on the quickmacros forum), May 26, 2006
    :: if exists renlef+_.bat goto FILEEXISTS
    @echo off
    set outfile=renlef+_
    if exist "%outfile%.bat" del "%outfile%.bat"
    if %1.==. (set /a exitcode=98&goto USAGE)
    if %2.==. (set /a exitcode=98&goto USAGE)
    set adn=%1&set delm=%2&set ext=%3&set space=%4&set doall=%5&&set count=0
    if %doall%.==1. goto SIMPLE

    for %%a in (*.%ext%) do (
    if %space%.==1. (
         echo %%a| find "%adn% %delm% "
         if errorlevel 1 (set /a count+=1&echo ren "%%a" "%adn% %delm% %%a"  >> "%outfile%.bat" ))
    if NOT %space%.==1. (
          echo %%a | find "%adn%%delm%"
         if errorlevel 1 (set /a count+=1&echo ren "%%a" "%adn%%delm%%%a" >> "%outfile%.bat"     ))
    goto :DONE
    ::  separated routine here 'cause wasn't able to integrate 'cause of weird behaviour in msdos on Win2K
    :: e.g. if you SET XX=YY, then echo "%XX%" doesn't give us XX's value within a FOR loop, but only on exit from loop
    for %%a in (*.%ext%) do (
         set /a count+=1
         if %space%.==1. echo ren "%%a" "%adn% %delm% %%a"  >> "renlef+_.bat"
         if NOT %space%.==1.      echo ren "%%a" "%adn%%delm%%%a" >> "renlef+_.bat")

    if %count%==0 (
         echo No files found that match criteria.&echo.
         set /a exitcode=97
         goto usage
    type renlef+_.bat
    echo type: %outfile%         To rename the above %count% files files! Or edit %outfile%.bat
    goto :EOF

    exit /B %exitcode%

    echo renall.bat exists. (Check ^& ) Delete file first.
    exit /B 99
    :: renlef-.bat
    ::  - Prefix REMOVAL utility for file names: Cuts the specified prefix that precedes a space and/or the specified delimiters in a file name
    :: As a precaution:
    :: -- All rename commands are generated & then displayed on screen
    :: -- All rename commands are written to a file which can be run  (after any optional or required user's edits)
    :: Arguments:
    ::    %1 - Word to remove
    ::    %2 - Optional delimiters, in addition to the default space, that separate %1 from the part you want to keep
    ::    %3 - Extension of file
    :: E.g. to remove initial "PART" from all files that start with "PART # ":
    ::     renlef- PART #
    :: v1.01 By Ravinder Singh ('wiz' on the quickmacros forum), May 26, 2006
    @echo off
    if %1.==. (set /a exitcode=98&goto usage)
    set cut=%1&set delims=%2&set ext=%3&set outfile=renlef-_&set count=0
    if exist "%outfile%.bat" del "%outfile%.bat"
    ::if not exist  "%outfile%.bat" set writeToFile=1
    set writeToFile=1

    :: Let user see and verify all rename commands before we execute them
    for /f "usebackq delims=" %%i in (`dir /b %cut%*.%ext%`) do @call :TEST "%%i"

    if %count%==0 (
         echo No files found that match criteria.&echo.
         set /a exitcode=97
         goto usage
    echo type: %outfile%           To rename the above %count% files! Or edit %outfile%.bat
    goto :EOF

    set /a count+=1
    set name=%1
    FOR /f  "usebackq tokens=1,2,3 delims=%delims% " %%j IN (`echo %name%`) DO @set mycmd=ren %name% "%%k
    echo %mycmd%
    if %writeToFile%==1 echo %mycmd% >> %outfile%.bat
    goto :EOF

    echo usage: %~nx0   LEFT-TRIM-STRING   DELIMS    EXTENSION
    exit /B %exitcode%

    :: Other notes
    :: original basic routine, with delimiters being "- "
    ::for /f "usebackq tokens=1,2,3  delims=- " %%i in (`dir /b %1*`) do echo ren "%%i - %%j" "%%j"
    :: 1* -- Optional code, can use if you don't want to create %output%.bat
    :: Now prompt whether or not to do the batch rename
    set/p input=Enter y to execute the above commands, anything else to quit:  
    if not %input%.==y. goto :EOF
    for /f "usebackq delims=" %%i in (`dir /b %cut%*.%ext%`) do @call :RENAMEALL "%%i"
    goto :EOF
    set name=%1
    FOR /f  "usebackq tokens=1,2,3 delims=%delims% " %%j IN (`echo %name%`) DO ren %name% "%%k
    goto :EOF
    Good Question?

    Featured Post

    Course: Foundations of Front-End Development

    Jump-start a lucrative career in front-end web development, with zero previous coding experience required. This course covers the basic programming concepts and languages required for creating engaging websites from scratch.

    Top Expert Contributor

    Essential articles and videos from the Experts

    Using dates in 'DOS' batch files has always been tricky as it has no built in ways of extracting date information.  There are many tricks using string manipulation to pull out parts of the %date% variable or output of the date /t command but these r…
    TOMORROW TOMORROW.BAT is inspired by a question I get asked over and over again; that is, "How can I use batch file commands to obtain tomorrow's date?" The crux of this batch file revolves around the XCOPY command - a technique I discovered w…
    In this video tutorial I show you the main steps to install and configure  a VMware ESXi6.0 server. The video has my comments as text on the screen and you can pause anytime when needed. Hope this will be helpful. Verify that your hardware and BIO…
    We often encounter PDF files that are pure images, that is, they do not have text characters, but instead contain only raster graphics. The most common causes of this are document scanning software and faxing software/services that create image-only…

    More valuable questions with Expert answers

    Question: I'm using a script that I got from here which automates a mySQL dump of all databases, .zip's them, and then deletes all the .zip files older that what you specify: ...

    Answer: The screenshot helped; the issue is probably the definition of the %backupfldr% variable: remove the trailing backslash in "C:\MySQLDumps\".

    Question: Hello all, I am not any means an expert in creating scripts but I have the following hoping to get it working the way I need it to. The below script works great when I need to delete all the empty folders that are in the top level. The...

    Answer: Just wrap your original script inside another loop that will feed it the subfolders one by one. This is in test mode and will not delete anything because of the uppercase ECHO in line 6 right before the "rd" (but it won't show anything either,...

    Question: I have a batch script that accepts as the argument a directory. I need to first check to see if the last character of the string ends with \ and remove it, if it does. I also need to replace all \ with /. I attempted a solution for this second...

    Answer: Give this a try, I think it gets the job done. Questions welcome. I assume "jars" should not have a / right before it, right, it just appends to the current folder name? It that's wrong just place a slash before the "jars" in that set. ...

    Question: We've moved out VAMT server to a new one, however we can't do a DNS redirect from the server one to the new server due to another process being run on the old server. I want to run a batch file as a GPO to send the computers using keys to the...

    Answer: After testing everyone's input, and running evaluation tests myself, I've reduced the problem to one of a GPO issue that can be resolved locally. t\TNK YOU EVERYONE FOR YOUR INPUT AND SUGGESTIONS.


    Extend your technology team with the Experts Exchange community.

    — trusted by —

    Who answers my questions?Our community has technology experts around the world.






    Expert in:

    • MS SQL Server
    • Powershell
    • VPN
    • MS DOS
    • MS SQL Server 2008

    Bill Prew



    Expert in:

    • MS DOS
    • VB Script
    • Windows Batch
    • Scripting Languages
    • MS Excel




    Expert in:

    • Windows 7
    • Windows Batch
    • Windows OS
    • Windows Server 2008
    • Active Directory

    Joe Winograd





    Expert in:

    • Document Imaging
    • Windows 7
    • Adobe Acrobat
    • Document Management
    • Images and Photos

    Dave Baldwin





    Expert in:

    • PHP
    • CSS
    • HTML
    • JavaScript
    • MySQL Server

    John Hurst





    Expert in:

    • Windows 7
    • MS Legacy OS
    • Outlook
    • Windows OS
    • Hardware-Other






    Expert in:

    • MS DOS
    • Windows Batch






    Expert in:

    • MS DOS
    • Windows Batch
    • VB Script






    Expert in:

    • Windows XP

    RELATED TOPICS view all topics

    1. Windows Batch
    2. Windows XP
    3. VB Script
    4. Windows OS
    5. MS Legacy OS
    6. Programming-Other
    7. Windows Server 2003
    8. Scripting Languages
    9. Windows 7
    10. Shell Scripting