Removing part of filename with batch

荒凉一梦 提交于 2019-12-25 18:12:09

问题


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!


回答1:


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"
  )
)



回答2:


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


来源:https://stackoverflow.com/questions/37863134/removing-part-of-filename-with-batch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!