Search code examples
batch-filefile-rename

Removing part of filename with batch


I've tried to tweak a lot of the code provided to similar questions, but I don't think the solution is posted. My problem is that the part from where I want to remove the rest exists 2 times before the last!

What I have is a folder with:

number1-number2-number3 - some random text about the file.filetype

number1 will range from 01 to 99
number2 will range from 1-99999
number3 will range from 1-999 with the possibility of 2 decimals, separated from whole number by .

Example folder c:\temp\:

15-1592-1 - file 1.doc
15-1592-2 - this is file2.pdf
15-1592-3 - this cointains subfiles.html
15-1592-3.1 - sub1.jpg
15-1592-3.2 - sub2.pdf

What I need is a folder where everything after the end of number3 is removed from the filename, but also the file type unaltered.

Example:

15-1592-1.doc
15-1592-2.pdf
15-1592-3.html
15-1592-3.1.jpg

I understand this is quiet possible from reading all the answers combined.

What I lack is the knowledge to compile it all!


Solution

  • You want to delete everything after the first space (without the extension)
    This is quite easy, if you use modifiers (see for /?):

    @echo off
    setlocal enabledelayedexpansion
    for %%a in (??-*-*) do (
      for /f "tokens=1 delims= " %%b in ("%%~na") do (
         ECHO ren "%%a" "%%b%%~xa"
      )
    )