Search code examples
batch-filebatch-processingdirbatch-rename

Batch : Rename a file according to the dir command


I have an issue to rename a file to a result of a dir. Example :

I have a folder name candidate in C drive and inside candidate folder there is below files :

  1. something.txt
  2. everything.doc
  3. onething.bmp

When I dir , I will get the listing of the files.

In the folder will always be 1 txt file and 1 bmp file

How can I rename the BMP file so it will have the same name as the TXT file assuming that I use dir *.txt

In the example above how can I change onething.bmp to something.bmp

Thanks in advance for any answers


Solution

  • for %%X in ("*.txt") do (
     for %%Y in ("*.bmp") do (
      echo ren %%Y %%~nX%%~xY
     )
    )
    

    remove the echo if the output is what you need.

    For explanation of %%~nX etc. see for /?