Removing part of filename with batch

2019-09-20 04:48发布

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!

2条回答
爷的心禁止访问
2楼-- · 2019-09-20 05:28

its' a little bit tricky to extract the decimal part (if present), but this should do the job (may need some token adjustment to fit your needs)

@echo off

setlocal enabledelayedexpansion

set "source_path=c:\temp\*"

for /f "tokens=1,* delims=." %%a in ('dir /b %source_path%') do (
  set "ext=" & set "decimal="
  for /f "tokens=1,* delims=." %%i in ("%%b") do (
    if "%%j" neq "" (
       set "ext=%%j"
       for /f "tokens=1,* delims=- " %%d in ("%%i") do set "decimal=.%%d"
    ) else (
       set "ext=%%i"
    )
  )
  for /f "tokens=1-3,* delims=- " %%i in ("%%a") do (
    rem replace echo with operation you need 
    echo %%i-%%j-%%k!decimal!.!ext!
  )  
)  

endlocal
查看更多
何必那么认真
3楼-- · 2019-09-20 05:31

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"
  )
)
查看更多
登录 后发表回答